Simply take a look at the use of the sort method of list in Python (or the sorted built-in function).
The elements of a list can be a variety of things, strings, dictionaries, classes of their own definition, and so on.
The sorted function uses the following:
Sorted (data, Cmp=none, Key=none, Reverse=false)
Where data is to be sorted, you can make list or iterator, CMP, and key are functions, and the two functions work with the elements of data to produce a result, and the sorted method is sorted according to this result.
CMP (E1, E2) is a comparison function with two parameters, the return value: Negative Number: E1 < e2, 0:e1 = = e2, positive: E1 > E2. The default is None, which is the built-in comparison function.
Key is a function with one parameter, which is used to extract the comparison value for each element. The default is None, which is to directly compare each element.
In general, key and reverse are much faster than CMP because they are processed only once for each element; And CMP handles it many times.
Use examples to illustrate the usage of sorted:
1. Sorting a list of tuple components
Sort using the key function (for lambda use see note 1)
>>> sorted (students, KEY=LAMBDA student:student[2])
Sort by CMP function
Use the operator function to speed up the order, which is equivalent to: (see note 2 for itemgetter usage)
Multilevel sorting with operator function
2. Sort by dictionary
Note 1
Reference: http://jasonwu.me/2011/10/29/introduce-to-python-lambda.html
NOTE 2
Reference: http://ar.newsmth.net/thread-90745710c90cf1.html
Equivalent
def itemgetter (i,*a): def func (obj): r = obj[i] If a: R = (r,) + tuple (Obj[i] for i in a) return r
return func >>> a = [2] >>> b=operator.itemgetter (1) >>> B (a) >>> b=operator.itemgetter (1,0) >>> B (a) (2, 1) >>> b=itemgetter (1) >>> B (a) 2 >>> b=itemgetter (1,0) >>> B (a) (2, 1)
Resources:
1. http://www.linuxso.com/linuxbiancheng/13340.html
2. http://www.douban.com/note/13460891/