pythonsort参数_Python sort()函数有哪些参数?

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工作much faster。

key应该是一个函数,它接受一个项并返回一个要比较和排序的值。reverse允许反转排序顺序。

使用key参数

您可以使用operator.itemgetter作为一个关键参数来按元组中的第二个、第三个等项排序。

示例>>> 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。

尤其是itemgetter,创建这样一个函数,从操作数中获取给定项。其文档中的一个示例:After, f=itemgetter(2), the call f(r) returns 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]会使排序更快。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值