Python 中,当我们需要对给定的list进行排序的时候,1. 可以用List的成员函数sort进行排序,2. 用build-in函数sorted进行排序
首先,我们先用help方法来看一下list.sort和sorted的区别
print help(sorted)
# result
Help on built-in function sorted in module __builtin__:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
print help(list.sort)
# result
Help on method_descriptor:
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
lterable是可迭代的类型
cmp用于比较函数,比较什么由key决定,有默认值,迭代集合中的一项。
key 用于列表元素的某个属性和函数进行作为关键词,有默认值,迭代集合中的一项。
reverse 排序规则,True或者False,默认为False
返回值是一个经过排序的可迭代类型。
P.S. 一般来说,cmp和key可以使用lambda表达式。
sort()和sorted()的不同在于,sort是把原来列表重新排列,而sorted是产生一个新的列表
l = [5, 2, 3, 1, 4]
# return a new sort list
print sorted([5, 2, 3, 1, 4])
# sort the original list
l.sort()
print l
# result
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
cmp 和 key
l = [('b', 1), ('a', 3), ('c', 2), ('d', 4)]
print sorted(l, cmp=lambda x, y: cmp(x[0], y[1]))
print sorted(l, key=lambda x: x[0]) # 想要如上的话,key=lambda x:(x[1],x[0])
# result
[('b', 1), ('a', 3), ('c', 2), ('d', 4)]
[('a', 3), ('b', 1), ('c', 2), ('d', 4)]
都是对于tuple中的第几个关键词进行排序比较。相对来说,key的效率比cmp快。
reverse
print sorted([5, 2, 3, 1, 4], reverse=True)
print sorted([5, 2, 3, 1, 4], reverse=False)
# result
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
很简单,就是输出是否是倒叙。