# python 系统学习笔记（十四）---排序

2013-03-12

Python 中, 当需要对一个 list 排序时, 一般可以用 list.sort() 或者 sorted(iterable[, cmp[, key[, reverse]]]).

cmp(e1, e2) 是带两个参数的比较函数, 返回值: 负数: e1 < e2, 0: e1 == e2, 正数: e1 > e2. 默认为 None, 即用内建的比较函数.
key 是带一个参数的函数, 用来为每个元素提取比较值. 默认为 None, 即直接比较每个元素.
reverse 是一个布尔值, 表示是否反转比较结果.
1.cmp

def my_cmp(E1, E2):
return -cmp(E1[1], E2[1]) #compare weight of each 2-tuple
#return the negative result of built-in cmp function
#thus we get the descend order
L = [(&#39;a&#39;, 11), (&#39;b&#39;, 10), (&#39;c&#39;, 12)]
L.sort(my_cmp)
print L
2.按照key 排序 这个会比cmp 执行次数少
def my_key(E1):
return E1[1] #return key 11,10,12
L = [(&#39;a&#39;, 11), (&#39;b&#39;, 10), (&#39;c&#39;, 12)]
L.sort(key=my_key,reverse=1) #key 大到小 reverse=0 时候从小到大
print L
3. itemgetter 返回 多排序

[python]
from operator import itemgetter, attrgetter
a = [1,2,3]
b=itemgetter(1)
print b(a)
b=itemgetter(1,0)
print b(a)
b=itemgetter(1)
print b(a)
b=itemgetter(1,0)
print b(a)

[python]
from operator import itemgetter, attrgetter
L = [(&#39;a&#39;, 11), (&#39;b&#39;, 10), (&#39;c&#39;, 12)]
L.sort(key=itemgetter(1))
print L

[python]
from operator import itemgetter, attrgetter
L = [(&#39;a&#39;, 11,&#39;B&#39;), (&#39;b&#39;, 11,&#39;A&#39;), (&#39;c&#39;, 12,&#39;C&#39;)]
L.sort(key=itemgetter(1,2))
print L
4 对由字典排序
[python]
d = {&#39;data1&#39;:3, &#39;data2&#39;:1, &#39;data3&#39;:2, &#39;data4&#39;:4}
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
print d

[python]
d = {&#39;data1&#39;:3, &#39;data2&#39;:1, &#39;data3&#39;:2, &#39;data4&#39;:4}
a=sorted(d.iteritems(), key=itemgetter(1), reverse=True)
print a

[python]
#1.
L = [(&#39;a&#39;, 11), (&#39;b&#39;, 10), (&#39;c&#39;, 12)]
L.sort(lambda elem1,elem2: cmp(elem1[1],elem2[1]))
print L
#2.
L = [(&#39;a&#39;, 11), (&#39;b&#39;, 10), (&#39;c&#39;, 12)]
L.sort(key=lambda elem: elem[1])
print L