The Python list built-in sort () method is used for sorting, or the Python built-in global sorted () method can be used to generate a new sequence for an iterative sequence ordering.
Sorted (Iterable,key=none,reverse=false), returns a new list that is valid for all objects that can be iterated
Sort (key=none,reverse=false) change list in place reverse:true reverse order; False Positive Order
Example1:
>>>sorted ([1,5,3,2,9])
[1,2,3,5,9]
>>>a=[5,3,2,1,4]
>>>a.sort ()
>>>a
[1,2,3,4,5] #若用list. Sort () the list itself will be modified
>>>sorted ({1: ' D ', 2: ' B ', 3: ' B ', 4: ' E ', 5: ' A '})
[1,2,3,4,5] #sorted () is valid for all iteration sequences
At python2.4 start, list.sort () and sorted () Add the key parameter to specify a function that is called before each element is compared.
Example2:
>>>sorted ("This was a test string from Andrew". Split (), Key=str.lower) #加了key, ignoring case
[' A ', ' Andrew ', ' from ', ' was ', ' string ', ' test ', ' this '] #key =len sorted by length
>>>sorted ("This was a test string from Andrew". Split ()) #未加key, default uppercase in front, lowercase in the rear
[' Andrew ', ' This ', ' a ', ' from ', ' is ', ' string ', ' test ']
It is more of a case to sort complex objects with certain values of complex objects.
Example3:
>>> student_tuples = [(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', 10),]
>>> Sorted (student_tuples, Key=lambda student:student[2]) # Sort by age
[(' Dave ', ' B ', ten), (' Jane ', ' B ', '), (' John ', ' A ', 15)]
>>>student_tuples.sort (Key=lambda x:x[2])
[(' Dave ', ' B ', ten), (' Jane ', ' B ', '), (' John ', ' A ', 15)]
Example4:
>>>s= "hello79351worldmynameismrfiona0352231964"
>>> ". Join (Sorted (S,key=lambda x: (X.isdigit (), X.isdigit () and int (x)%2==0,x.islower (), X.isupper (), x)))
' FHIMMNWaadeeilllmnooorrsy113335579902246 '
Uppercase before, lowercase in, number last and odd before even
>>>s={' A ': ten, ' t ': 5, ' C ': 2, ' B ': 12}
>>>sorted (S,key=lambda x:x[0])
[' A ', ' B ', ' C ', ' t ']
>>>s=[]
Python sort sorted and sort comparison