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]會使排序更快。
總結
以上是生活随笔為你收集整理的pythonsort参数_Python sort()函数有哪些参数?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何短时间突击 Java面试?附刷题神器
- 下一篇: fcntl设置FD_CLOEXEC