Python中有有兩種方法進行List排序:函數
1. 用List的成員函數sort進行排序;ui
2. 用built-in函數sorted進行排序(從2.4開始);spa
API:code
sortblog
sorted排序
iterable:是迭代的類型;it
cmp:用於比較的函數,具體比較,由key決定,有默認值,迭代集合中的一項;class
key:用列表元素的某個屬性和函數進行做爲關鍵字,有默認值,迭代集合中的一項;效率
reverse:爲True是正序,爲False是反序;import
備註:key和cmp,可使用lambda表達式;
Sort Reverse
True
1 >>> list=[5, 2, 3, 1, 4] 2 >>> print sorted(list,reverse=True) 3 [5, 4, 3, 2, 1]
False
1 >>> list=[5, 2, 3, 1, 4] 2 >>> print sorted(list,reverse=False) 3 [1, 2, 3, 4, 5]
Sort cmp
1 >>> L=[('b',2),('c',3),('a',1),('d',4)] 2 >>> print sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) 3 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Sort key
1 >>> L=[('b',2),('c',3),('a',1),('d',4)] 2 >>> print sorted(L, key=lambda x:x[1]) 3 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
備註:key的效率比cmp高
例子:
import math import os his = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0 , 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 2, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 3, 1, 3, 3, 0, 0, 0, 0, 0, 0, 1, 0, 3, 2, 132, 1, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 15, 0 , 1, 0, 1, 0, 0, 8, 1, 0, 0, 0, 0, 1, 6, 0, 2, 0, 0, 0, 0, 18, 1, 1, 1, 1, 1, 2, 365, 115, 0, 1, 0, 0, 0, 135, 186, 0, 0, 1, 0, 0, 0, 116, 3, 0, 0, 0, 0, 0, 21, 1, 1, 0, 0, 0, 2, 10, 2, 0, 0, 0, 0, 2, 10, 0, 0, 0, 0, 1, 0, 625] values = {} for i in range(256): values[i] = his[i] for j,k in sorted(values.items(),key=lambda x:x[1],reverse = True)[:10]: print j,k