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