Python sort()函数有哪些参数?
除了 key
这个参数,还有其他的参数吗?比如说:value
?
3 个回答
1
是的,它需要其他参数,但没有 value
这个参数。
>>> print list.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
那 value
这个参数到底代表什么呢?
3
除了 key=
这个参数,Python 2.x 中列表的 sort
方法还可以使用 cmp=
参数(不过这不是个好主意,因为在 Python 3 中已经去掉了这个功能)。无论你用不使用这两个参数,你总是可以加上 reverse=True
来让排序结果变成降序(默认是升序,也可以通过 reverse=False
明确要求升序,如果你真的有这个需求的话)。至于你提到的 value
参数,我不太清楚它是用来干什么的。
41
sort
和sorted
的参数
sort
和sorted
都有三个关键字参数:cmp
、key
和reverse
。
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
使用key
和reverse
更好,因为它们的运行速度比cmp
快很多。
key
应该是一个函数,这个函数接收一个项目并返回一个用于比较和排序的值。reverse
可以让你反转排序的顺序。
使用key
参数
你可以使用operator.itemgetter
作为key
参数,这样可以按元组中的第二个、第三个等项目进行排序。
示例
>>> from operator import itemgetter
>>> a = range(5)
>>> b = a[::-1]
>>> c = map(lambda x: chr(((x+3)%5)+97), a)
>>> sequence = zip(a,b,c)
# sort by first item in a tuple
>>> sorted(sequence, key = itemgetter(0))
[(0, 4, 'd'), (1, 3, 'e'), (2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c')]
# sort by second item in a tuple
>>> sorted(sequence, key = itemgetter(1))
[(4, 0, 'c'), (3, 1, 'b'), (2, 2, 'a'), (1, 3, 'e'), (0, 4, 'd')]
# sort by third item in a tuple
>>> sorted(sequence, key = itemgetter(2))
[(2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c'), (0, 4, 'd'), (1, 3, 'e')]
解释
序列可以包含任何对象,甚至是不可比较的对象,但如果我们能定义一个函数,能为每个项目生成可以比较的东西,我们就可以把这个函数传递给sort
或sorted
的key
参数。
特别是,itemgetter
创建了这样一个函数,它从操作数中提取给定的项目。以下是它文档中的一个示例:
在
f=itemgetter(2)
之后,调用f(r)
会返回r[2]
。
迷你基准测试,key
与cmp
出于好奇,比较了key
和cmp
的性能,数值越小越好:
>>> from timeit import Timer
>>> Timer(stmt="sorted(xs,key=itemgetter(1))",setup="from operator import itemgetter;xs=range(100);xs=zip(xs,xs);").timeit(300000)
6.7079150676727295
>>> Timer(stmt="sorted(xs,key=lambda x:x[1])",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)
11.609490871429443
>>> Timer(stmt="sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)
22.335839986801147
所以,使用key
进行排序的速度至少是使用cmp
的两倍。用itemgetter
代替lambda x: x[1]
会让排序更快。