2011-04-24 78 views
0

你如何排序元組的列表由elemant多數民衆贊成? 下面說一下是列表LL。 欲ID2排序 - LL [1],這是一個元組爲遞增。 我該怎麼做。在python排序元組列表?

  Id, Id2 CCC 
      A123 A120 '2011-03' 
    LL=  A133 A123 '2011-03' 
      D123 D120 '2011-04' 
      D140 D123 '2011-04' 
+0

'ID2 - LL [1],這是一個元組作爲asc' - * *什麼? – ThiefMaster 2011-04-24 20:54:12

+0

我通過ID2要排序,ASC – Merlin 2011-04-24 20:57:14

回答

4

看一看http://wiki.python.org/moin/HowTo/Sorting/

sorted(LL, key=itemgetter(1))可能會做你想要什麼。

請注意,您必須from operator import itemgetter得到itemgetter功能。

In [1]: LL = (('A123', 'A120', '2011-03'), ('A133', 'A123', '2011-03'), ('D123', 'D120', '2011-04'), ('D140', 'D123', '2011-04')) 

In [2]: from operator import itemgetter 

In [3]: sorted(LL, key=itemgetter(1)) 
Out[3]: 
[('A123', 'A120', '2011-03'), 
('A133', 'A123', '2011-03'), 
('D123', 'D120', '2011-04'), 
('D140', 'D123', '2011-04')] 
+0

不要緊,該鍵= itemgetter(1)是一個元組 – Merlin 2011-04-24 20:54:47

+0

'鍵= itemgetter(1)'將'排序()在'LL每個元素'取得與指數產品1 '。請實際讀取我鏈接到頁面,它解釋它:http://wiki.python.org/moin/HowTo/Sorting/#Operator_Module_Functions – ThiefMaster 2011-04-24 20:57:52

+0

我一直在試圖找出這個了一會兒。我找到了我的概率。數據庫具有排序列作爲主鍵,不斷更改我的訂單。 ;-)))))!謝謝 – Merlin 2011-04-24 21:17:03

0

你可以去:

 
LL.sort(key=lambda x:x[1]) 

其中1是元組的元素的索引。

+1

更好地使用'operator'模塊中的'itemgetter(1)'。否則,需要爲每個項目調用一個python函數(如果使用默認的CPython實現,那麼'operator'函數就用C編寫) – ThiefMaster 2011-04-24 20:58:46