python list 排序問題
對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)]
相關文章
- python list 排序Python排序
- Python list,dict問題解答Python
- python如何將list排序Python排序
- Python 疑難問題:[] 與 list() 哪個快?Python
- SQL Where in list 問題SQL
- 字串排序問題字串排序
- group by 排序問題排序
- Collections排序問題!!排序
- 中文排序 問題排序
- Python 字串,list排序,刪除重複資料Python字串排序
- 章節排序問題排序
- oracle中排序問題Oracle排序
- Java中List的排序Java排序
- C# list物件排序C#物件排序
- python list排序的兩種方法及例項講解Python排序
- 兩個小問題深入淺出List的效能問題
- java中list的常見問題。Java
- corosync 解決 [TOTEM ] Retransmit List: 問題ROSMIT
- Array.sort排序問題排序
- 彩虹排序 | 荷蘭旗問題排序
- connect by 的排序問題排序
- Java基礎系列—List排序Java排序
- Python List 列表list()方法Python
- 【SQL 學習】排序問題之order by與索引排序SQL排序索引
- List資料多重規則排序排序
- Python List 列表list()方法分享Python
- python listPython
- 面試題:陣列按列排序的問題面試題陣列排序
- C語言解決排序問題C語言排序
- 單連結串列的排序問題排序
- 這就是選擇排序的問題排序
- 分頁查詢的排序問題排序
- 索引無法消除排序的問題索引排序
- SQL SERVER和ORACLE的排序問題SQLServerOracle排序
- List排序用Collections.sort and Comparator排序
- Python之list,string,tuple,dict練習題Python
- List面試題面試題
- python列表(List)Python