Python-how to sort
- Overview
- Key function (★★★★★)
- OPerator module functions
- ASC and DESC Ascending and descending
Overview
For the Python list, there is a method List.sort (), plus a built-in function sorted ()
List.sort () is a sort of itself that does not produce new objects. Instead, sorted receives an iterative object that returns a new, ordered list
Help on built-in/, *, Key=none, reverse=False) from in ascending order. and the in descending order
>>> help (List.sort)-on Method_descriptor:sort (...) L.sort (Key=none, Reverse=false), None--stable sort *in place*
List.sort () modifies the original list to return None, which is more efficient when you don't need the original list.
>>> a=[3,5,2,1]>>> a.sort ()>>> a[1, 2, 3, 5]
Sorted () This method is more convenient to use.
>>> sorted ([6,3,8,12,4]) [3, 4, 6, 8, a]
Sorted () receives an iterative object
eg.
Like what
>>> dic={4:'a', 2:'b', 3:'a' , 1:'h'}>>> sorted (DIC) [1, 2, 3, 4]
Key function
Both List.sort () and sorted () has a key parameter to specify a function to being called on the each list element
Prior to making comparisons
Both List.sort () and sorted () have a key parameter that specifies the function that is called on each list element before it is compared.
For example:
>>> Sorted ("This was a test string from Andrew". Split (), key=str.lower) ['a','Andrew',' from',' is','string','Test',' This']
The value of the key parameter should be a function this takes a single argument and returns a key to use
For sorting purposes. This technique are fast because the key function is called exactly once for each input
Record
The value of the key parameter should be a function object, which takes a parameter and returns a key, which is the standard for sorting,
classStudent (object):def __init__(self,name,grade,age): Self.name=name Self.grade=Grade Self.age= Agedef __repr__(self):returnrepr ((self.name,self.grade,self.age)) Ls_grade=Sorted ([Student ('Join', 90,15), Student ('Alex', 87,13), Student ('Eleven', 100,17)],key=Lambdastu:stu.grade) Ls_age=Sorted ([Student ('Join', 90,15), Student ('Alex', 87,17), Student ('Eleven', 100,14)],key=Lambdastu:stu.age)Print(Ls_grade)Print(Ls_age)
OPerator module functions
ASC and DESC Ascending and descending
The default is ascending sort
Reverse default is False, if true, it is descending order
The sort of sorted and list.sort () is a stable sort
Yu Yang back to the top of the
Python-how to sort