Sorting basic:
>>> print sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
>>> L = [5, 2, 3, 1, 4]
>>> L.sort()
>>> print L
[1, 2, 3, 4, 5]
Sorting cmp:
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Sorting keys:
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>print
sorted(L, key=lambda x:x[1]))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
Sorting reverse:
>>> print sorted([5, 2, 3, 1, 4], reverse=True)
[5, 4, 3, 2, 1]
>>> print sorted([5, 2, 3, 1, 4], reverse=False)
[1, 2, 3, 4, 5]
注:效率key>cmp(key比cmp快)
在Sorting Keys中:咱們看到,此時排序過的L是僅僅按照第二個關鍵字來排的,若是咱們想用第二個關鍵字
排過序後再用第一個關鍵字進行排序呢?
>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> print sorted(L, key=lambda x:(x[1],x[0]))
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]
例子:有一個文件,裏面一行記錄一條字符串,好比有數百行,固然有重複的,而後按獨立字符串出現的次數排序,print輸出.
#!/usr/bin/python
fp = open('map.txt', 'r')
lines = fp.readlines()
fp.close()
dic = {}
for line in lines:
line = line.strip()
if line == '':
continue
if line in dic:
dic[line] += 1
else:
dic[line] = 1
print dic.items()
mysort = sorted(dic.items(), key = lambda dic: dic[1], reverse=True)
print "mysort:" ,mysort