Python sort()函数有哪些参数? [英] What arguments does Python sort() function have?
问题描述
除了key
之外是否还有其他参数,例如:value
?
Is there any other argument than key
, for example: value
?
推荐答案
sort
和sorted
的参数
sort
和sorted
都有三个关键字参数:cmp
,key
和reverse
.
Arguments of sort
and sorted
Both sort
and sorted
have three keyword arguments: cmp
, key
and 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
.
Using key
and reverse
is preferred, because they work much faster than an equivalent cmp
.
key
应该是一个接受项目并返回值进行比较和排序的函数. reverse
允许反转排序顺序.
key
should be a function which takes an item and returns a value to compare and sort by. reverse
allows to reverse sort order.
您可以使用operator.itemgetter
作为关键参数来按元组中的第二,第三等进行排序.
You can use operator.itemgetter
as a key argument to sort by second, third etc. item in a tuple.
>>> 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')]
说明
序列可以包含任何对象,甚至不具有可比性,但是如果我们可以定义一个函数,该函数可以为每个项目进行比较,则可以将该函数在key
参数中传递给sort
或sorted
Explanation
Sequences can contain any objects, not even comparable, but if we can define a function which produces something we can compare for each of the items, we can pass this function in key
argument to sort
or sorted
.
itemgetter
创建这样的函数,该函数从其操作数中获取给定项.文档中的示例:
itemgetter
, in particular, creates such a function that fetches the given item from its operand. An example from its documentation:
在
f=itemgetter(2)
之后,调用f(r)
返回r[2]
.
After,
f=itemgetter(2)
, the callf(r)
returnsr[2]
.
迷你基准,key
与cmp
出于好奇,key
和cmp
的性能相比,越小越好:
Mini-benchmark, key
vs cmp
Just out of curiosity, key
and cmp
performance compared, smaller is better:
>>> 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]
可使排序更快.
So, sorting with key
seems to be at least twice as fast as sorting with cmp
. Using itemgetter
instead of lambda x: x[1]
makes sort even faster.
这篇关于Python sort()函数有哪些参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!