# python中对列表排序实例

cmp:cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument:
“cmp=lambda x,y: cmp(x.lower(), y.lower())”
key:key specifies a function of one argument that is used to extract a comparison key from each list element: “key=str.lower”
reverse:reverse is a boolean value. if set to true, then the list elements are sorted as if each comparison were reversed.in general, the key and reverse conversion processes are much faster than specifying an
equivalent cmp function. this is because cmp is called multiple times for each list element while key and reverse touch each element only once.

>>>l = [2,3,1,4]
>>>l.sort()
>>>l
>>>[1,2,3,4]

>>>l = [2,3,1,4]
>>>l.sort(reverse=true)
>>>l
>>>[4,3,2,1]

>>>l = [(‘b’,2),(‘a’,1),(‘c’,3),(‘d’,4)]
>>>l.sort(cmp=lambda x,y:cmp(x[1],y[1]))
>>>l
>>>[(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

>>>l = [(‘b’,2),(‘a’,1),(‘c’,3),(‘d’,4)]
>>>l.sort(key=lambda x:x[1])
>>>l
>>>[(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

>>>l = [(‘b’,2),(‘a’,1),(‘c’,3),(‘d’,4)]
>>>import operator
>>>l.sort(key=operator.itemgetter(1))
>>>l
>>>[(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

>>>l = [(‘b’,2),(‘a’,1),(‘c’,3),(‘d’,4)]
>>>a = [(x[1],i,x) for i,x in enumerate(l)] #i can confirm the stable sort
>>>a.sort()
>>>l = [s[2] for s in a]
>>>l
>>>[(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

cmp < dsu < key

>>>l = [(‘d’,2),(‘a’,4),(‘b’,3),(‘c’,2)]
>>> l.sort(key=lambda x:x[1])
>>> l
>>>[(‘d’, 2), (‘c’, 2), (‘b’, 3), (‘a’, 4)]

>>> l = [(‘d’,2),(‘a’,4),(‘b’,3),(‘c’,2)]
>>> l.sort(key=lambda x:(x[1],x[0]))
>>> l
>>>[(‘c’, 2), (‘d’, 2), (‘b’, 3), (‘a’, 4)]

>>> l = [(‘d’,2),(‘a’,4),(‘b’,3),(‘c’,2)]
>>> l.sort(key=operator.itemgetter(1,0))
>>> l
>>>[(‘c’, 2), (‘d’, 2), (‘b’, 3), (‘a’, 4)]

Posted in 未分类