python Sort the list
Just remember python in List Of sort Method ( perhaps sorted Built-in functions ) Usage of .
keyword :
python Sort the list python Dictionary sort sorted
List And the elements of it can be all kinds of things , character string , Dictionaries , Self defined classes, etc .
sorted Function usage is as follows :
sorted(data, cmp=None, key=None, reverse=False)
among ,data It's the data to be sorted , You can make List perhaps iterator, cmp and key It's all functions , These two functions act on data To produce a result ,sorted Methods sort based on this result .
cmp(e1, e2) Is a comparison function with two parameters , Return value : negative : e1 < e2, 0: e1 == e2, Positive numbers : e1 > e2. The default is None, Using the built-in comparison function .
key It's a function with one parameter , Used to extract comparison values for each element . The default is None, That is to compare each element directly .
Usually , key and reverse Than cmp Much faster , Because for each element they only process once ; and cmp I'll deal with it many times .
To illustrate by an example sorted Usage of :
1. Right tuple Composed of List Sort
students =[(‘john’,‘A’,15),(‘jane’,‘B’,12),(‘dave’,‘B’,10),]
use key Function order (lambda See notes for usage of 1)
sorted(students, key=lambda student : student[2])# sort by age [(‘dave’,‘B’,10),(‘jane’,‘B’,12),(‘john’,‘A’,15)]
use cmp Function order
sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))# sort by age [(‘dave’,‘B’,10),(‘jane’,‘B’,12),(‘john’,‘A’,15)]
use operator Function to speed up , The above sort is equivalent to :(itemgetter See notes for usage of 2)
from operator import itemgetter, attrgette sorted(students, key=itemgetter(2))
use operator Function for multi-level sorting
sorted(students, key=itemgetter(1,2))# sort by grade then by age [(‘john’,‘A’,15),(‘dave’,‘B’,10),(‘jane’,‘B’,12)]
2. Sort by Dictionary
d ={‘data1’:3,‘data2’:1,‘data3’:2,‘data4’:4} sorted(d.iteritems(), key=itemgetter(1), reverse=True) [(‘data4’,4),(‘data1’,3),(‘data3’,2),(‘data2’,1)]
That's all for this sharing ~ Pay attention before you go , Thank you for reading ~