python list 排序問題__python

來源:互聯網
上載者:User

對List進行排序,Python提供了兩個方法

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

list.sort(func=None, key=None, reverse=False) 
方法2.用序列類型函數sorted(list)進行排序

>>> list = [2,5,1]  >>> list  [2, 5, 1]  >>> sorted(list)  [1, 2, 5]  >>> list  [2, 5, 1]  >>> list.sort()  >>> list  [1, 2, 5]  

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

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

執行個體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(key=lambda x:x[1]) 
>>>L
>>>[('a', 1), ('c', 3), ('d', 4), ('b', 6)]

>>>L = [('b',2),('a',1),('c',3),('d',4)]

執行個體4:
>>>import operator
>>>L.sort(key=operator.itemgetter(1)) 
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

(operator模組詳細用法請參加上篇部落格。)


如果我們想用第二個關鍵字排過序後再用第一個關鍵字進行排序呢?有兩種方法 
執行個體5:
>>> 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)]
執行個體6:
>>> 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)]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.