A guide to the sort method for List in python
 20200402 14:02:07
 OfStack
Just a quick note of the use of the List sort method (or the builtin function sorted) in python.
The elements of a List can be anything from strings to dictionaries to selfdefined classes.
The sorted function is used as follows:
Sorted (data, CMP = None, key = None, reverse = False)
Where, data is the data to be sorted. You can make List or iterator, CMP and key all functions. These two functions act on the element of data to produce a result, which is sorted by the sorted method.
CMP (e1, e2) is a comparison function with two parameters, return value: negative: e1
<
E2, 0: e1 == e2, positive: e1
>
E2. Default to None, with the builtin comparison function.
Key is a function with one parameter to extract the comparison value for each element.
In general, key and reverse are much faster than CMP because they are only processed once for each element; The CMP does this multiple times.
I have an example to illustrate the use of sorted:
1. Sort a List of tuples
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
Sort by the key function (see note 1 for lambda usage)
>>> sorted(students, key=lambda student : student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Sort by the CMP function
>>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Use the operator function to speed things up, the sorting above is equivalent to :(see note 2 for itemgetter usage)
>>> from operator import itemgetter, attrgetter
>>> sorted(students, key=itemgetter(2))
Use the operator function for multiple levels of sorting
>>> sorted(students, key=itemgetter(1,2)) # sort by grade then by age
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
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)]
Note 1
Reference: (link: http://jasonwu.me/2011/10/29/introducetopythonlambda.html)
Note 2
Reference: http://ar.newsmth.net/thread90745710c90cf1.html
class itemgetter(__builtin__.object)
 itemgetter(item, ...) > itemgetter object

 Return a callable object that 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])
The equivalent of
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 = [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)
Reference:
1. (link: http://www.linuxso.com/linuxbiancheng/13340.html)
2. (link: http://www.douban.com/note/13460891/)