python list排序的兩種方法及執行個體講解

來源:互聯網
上載者:User
對List進行排序,Python提供了兩個方法

方法1.用List的內建函數list.sort進行排序

list.sort(func=None, key=None, reverse=False)

Python執行個體:

>>> list = [2,5,8,9,3]  >>> list  [2,5,8,9,3]  >>> list.sort()  >>> list  [2, 3, 5, 8, 9]

方法2.用序列類型函數sorted(list)進行排序(從2.4開始)

Python執行個體:

>>> list = [2,5,8,9,3]  >>> list  [2,5,8,9,3]  >>> sorted(list)  [2, 3, 5, 8, 9]

兩種方法的區別:

sorted(list)返回一個對象,可以用作運算式。原來的list不變,產生一個新的排好序的list對象。

list.sort() 不會返回對象,改變原有的list。

其他sort的執行個體:

執行個體1:正向排序

>>>L = [2,3,1,4]>>>L.sort()>>>L>>>[1,2,3,4]

執行個體2:反向排序

>>>L = [2,3,1,4]>>>L.sort(reverse=True)>>>L>>>[4,3,2,1]

執行個體3:對第二個關鍵字排序

>>>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)]

執行個體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)]

執行個體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)]

執行個體6:(DSU方法:Decorate-Sort-Undercorate)

>>>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排序的方法,其中執行個體3.4.5.6能起到對以List item中的某一項

為比較關鍵字進行排序.

效率比較:

cmp < DSU < key

通過實驗比較,方法3比方法6要慢,方法6比方法4要慢,方法4和方法5基本相當

多關鍵字比較排序:

執行個體7:

>>>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是僅僅按照第二個關鍵字來排的,

如果我們想用第二個關鍵字排過序後再用第一個關鍵字進行排序呢?有兩種方法

執行個體8:

>>> 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)]

執行個體9:

>>> 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)]

為什麼執行個體8能夠工作呢?原因在於tuple是的比較從左至右比較的,比較完第一個,如果

相等,比較第二個

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.