Take a quick look at the use of the Sort method (or sorted built-in function) of the list in Python.
The elements of a list can be various things, strings, dictionaries, classes that you define, and so on.
The sorted function uses the following:
Sorted (data, Cmp=none, Key=none, Reverse=false)
Where data is to be sorted, the list or iterator, CMP, and key are functions that produce a result on the elements of data, and the sorted method is sorted according to the result.
CMP (E1, E2) is a comparison function with two parameters, return value: Negative: E1 < e2, 0:e1 = = E2, positive number: E1 > E2. The default is None, that is, the built-in comparison function.
The key is a function with one parameter that is used to extract the comparison value for each element. Default to None, that is, to compare each element directly.
Typically, key and reverse are much faster than CMP because they are processed only once for each element; And CMP handles it multiple times.
Examples are used to illustrate the use of sorted:
1. Sort the list of tuple composed of
>>> students = [(' John ', ' A ',], (' Jane ', ' B ', '), (' Dave ', ' B ', 10),]
Sort with a key function (see note 1 for the use of lambda)
>>> sorted (students, KEY=LAMBDA student:student[2]) # Sort by age
[(' Dave ', ' B ',], (' Jane ', ' B ', 12) , (' John ', ' A ', 15)]
Sorting with CMP functions
>>> sorted (students, Cmp=lambda x,y:cmp (x[2], y[2)) # Sort by age
[(' Dave ', ' B ',], (' Jane ', ' B ', 12), ( ' John ', ' A ', 15)]
Using the operator function to speed up, the above sort is equivalent to: (see note 2 for itemgetter usage)
>>> from operator import Itemgetter, attrgetter
>>> sorted (students, Key=itemgetter (2))
Multilevel sorting with operator function
>>> sorted (students, key=itemgetter (1,2)) # Sort by grade then by age
2. Sort by dictionary
>>> d = {' Data1 ': 3, ' data2 ': 1, ' data3 ': 2, ' DATA4 ': 4}
>>> sorted (D.iteritems (), Key=itemgetter (1) , reverse=true)
Note 1
Reference: http://jasonwu.me/2011/10/29/introduce-to-python-lambda.html
NOTE 2
Reference: http://ar.newsmth.net/thread-90745710c90cf1.html
Class Itemgetter (__builtin__.object)
| itemgetter (item, ...)--> Itemgetter object
|
| Return a callable object this fetches the given item (s) from its operand.
| After, F=itemgetter (2), the call F (r) returns R[2].
| After, G=itemgetter (2,5,3), the call G (r) returns (R[2], r[5], r[3]
Equivalent
def itemgetter (i,*a):
def func (obj):
r = obj[i]
If a:
R = (r,) + tuple (Obj[i] for I-a) return
r
return func
>>> a = [1,2,3]
>>> b=operator.itemgetter (1)
>>> B (a)
2
>>> 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/