對List進(jìn)行排序,Python提供了兩個方法
方法1.用List的內(nèi)建函數(shù)list.sort進(jìn)行排序
list.sort(func=None, key=None, reverse=False)
Python實(shí)例:
1
2
3
4
5
6
|
>>> list = [ 2 , 5 , 8 , 9 , 3 ] >>> list [ 2 , 5 , 8 , 9 , 3 ] >>> list .sort() >>> list [ 2 , 3 , 5 , 8 , 9 ] |
方法2.用序列類型函數(shù)sorted(list)進(jìn)行排序(從2.4開始)
Python實(shí)例:
1
2
3
4
5
|
>>> list = [ 2 , 5 , 8 , 9 , 3 ] >>> list [ 2 , 5 , 8 , 9 , 3 ] >>> sorted ( list ) [ 2 , 3 , 5 , 8 , 9 ] |
兩種方法的區(qū)別:
sorted(list)返回一個對象,可以用作表達(dá)式。原來的list不變,生成一個新的排好序的list對象。
list.sort() 不會返回對象,改變原有的list。
其他sort的實(shí)例:
實(shí)例1:正向排序
1
2
3
4
|
>>>L = [ 2 , 3 , 1 , 4 ] >>>L.sort() >>>L >>>[ 1 , 2 , 3 , 4 ] |
實(shí)例2:反向排序
1
2
3
4
|
>>>L = [ 2 , 3 , 1 , 4 ] >>>L.sort(reverse = True ) >>>L >>>[ 4 , 3 , 2 , 1 ] |
實(shí)例3:對第二個關(guān)鍵字排序
1
2
3
4
|
>>>L = [( 'b' , 6 ),( 'a' , 1 ),( 'c' , 3 ),( 'd' , 4 )] >>>L.sort( lambda x,y: cmp (x[ 1 ],y[ 1 ])) >>>L >>>[( 'a' , 1 ), ( 'c' , 3 ), ( 'd' , 4 ), ( 'b' , 6 )] |
實(shí)例4: 對第二個關(guān)鍵字排序
1
2
3
4
|
>>>L = [( 'b' , 6 ),( 'a' , 1 ),( 'c' , 3 ),( 'd' , 4 )] >>>L.sort(key = lambda x:x[ 1 ]) >>>L >>>[( 'a' , 1 ), ( 'c' , 3 ), ( 'd' , 4 ), ( 'b' , 6 )] |
實(shí)例5: 對第二個關(guān)鍵字排序
1
2
3
4
5
|
>>>L = [( 'b' , 2 ),( 'a' , 1 ),( 'c' , 3 ),( 'd' , 4 )] >>> import operator >>>L.sort(key = operator.itemgetter( 1 )) >>>L >>>[( 'a' , 1 ), ( 'b' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )] |
實(shí)例6:(DSU方法:Decorate-Sort-Undercorate)
1
2
3
4
5
6
|
>>>L = [( 'b' , 2 ),( 'a' , 1 ),( 'c' , 3 ),( 'd' , 4 )] >>>A = [(x[ 1 ],i,x) for i,x in enumerate (L)] #i can confirm the stable sort >>>A.sort() >>>L = [s[ 2 ] for s in A] >>>L >>>[( 'a' , 1 ), ( 'b' , 2 ), ( 'c' , 3 ), ( 'd' , 4 )] |
以上給出了6中對List排序的方法,其中實(shí)例3.4.5.6能起到對以List item中的某一項(xiàng)
為比較關(guān)鍵字進(jìn)行排序.
效率比較:
cmp < DSU < key
通過實(shí)驗(yàn)比較,方法3比方法6要慢,方法6比方法4要慢,方法4和方法5基本相當(dāng)
多關(guān)鍵字比較排序:
實(shí)例7:
1
2
3
4
|
>>>L = [( 'd' , 2 ),( 'a' , 4 ),( 'b' , 3 ),( 'c' , 2 )] >>> L.sort(key = lambda x:x[ 1 ]) >>> L >>>[( 'd' , 2 ), ( 'c' , 2 ), ( 'b' , 3 ), ( 'a' , 4 )] |
我們看到,此時排序過的L是僅僅按照第二個關(guān)鍵字來排的,
如果我們想用第二個關(guān)鍵字排過序后再用第一個關(guān)鍵字進(jìn)行排序呢?有兩種方法
實(shí)例8:
1
2
3
4
|
>>> L = [( 'd' , 2 ),( 'a' , 4 ),( 'b' , 3 ),( 'c' , 2 )] >>> L.sort(key = lambda x:(x[ 1 ],x[ 0 ])) >>> L >>>[( 'c' , 2 ), ( 'd' , 2 ), ( 'b' , 3 ), ( 'a' , 4 )] |
實(shí)例9:
1
2
3
4
|
>>> L = [( 'd' , 2 ),( 'a' , 4 ),( 'b' , 3 ),( 'c' , 2 )] >>> L.sort(key = operator.itemgetter( 1 , 0 )) >>> L >>>[( 'c' , 2 ), ( 'd' , 2 ), ( 'b' , 3 ), ( 'a' , 4 )] |
為什么實(shí)例8能夠工作呢?原因在于tuple是的比較從左到右比較的,比較完第一個,如果相等,比較第二個
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持服務(wù)器之家!
原文鏈接:http://blog.chinaunix.net/uid-20775448-id-4222915.html