2014-02-27 72 views
3

如何按第一個元素的數量對列表進行排序?例如,如果我在下面列出了以下列表,我希望將列表排序,以便所有的「格魯吉亞大學」參賽作品排在第一位,然後是「密歇根大學」參賽作品,然後是「佛羅里達大學」條目。Python:如何按最常見的第一個元素對列表進行排序?

l = [['University of Michigan','James Jones','phd'], 
    ['University of Georgia','Anne Greene','ba'], 
    ['University of Michigan','Frank Kimball','ma'], 
    ['University of Florida','Nate Franklin','ms'], 
    ['University of Georgia','Sara Dean','ms'], 
    ['University of Georgia','Beth Johnson','bs']] 

回答

9
from collections import Counter 
c = Counter(item[0] for item in l) 
print sorted(l, key = lambda x: -c[x[0]]) 

輸出

[['University of Georgia', 'Anne Greene', 'ba'], 
['University of Georgia', 'Sara Dean', 'ms'], 
['University of Georgia', 'Beth Johnson', 'bs'], 
['University of Michigan', 'James Jones', 'phd'], 
['University of Michigan', 'Frank Kimball', 'ma'], 
['University of Florida', 'Nate Franklin', 'ms']] 

香草字典版本:

c = {} 
for item in l: 
    c[item[0]] = c.get(item[0], 0) + 1 
print sorted(l, key = lambda x: -c[x[0]]) 

defaultdict版本:

from collections import defaultdict 
c = defaultdict(int) 
for item in l: 
    c[item[0]] += 1 
print sorted(l, key = lambda x: -c[x[0]]) 
+0

+1從u學到很多東西;) – zhangxaochen

+0

@zhangxaochen歡迎您:)你善於numpy的自己:) – thefourtheye

+0

待辦事項不要忘記,Python 2.6.6中不存在Counter,因此如果以後的Python不可用,就不能使用它。 – sabbahillel

-1

從這裏獲取解決方案:How to sort a list of lists by a specific index of the inner list?

from operator import itemgetter 

L=[['University of Michigan','James Jones','phd'],['University of Georgia','Anne Greene','ba'],['University of Michigan','Frank Kimball','ma'],['University of Florida','Nate Franklin','ms'],['University of Georgia','Sara Dean','ms'],['University of Georgia','Beth Johnson','bs']] 

print 'Before:', L 
print ' After:', sorted(L, key=itemgetter(0)) 

輸出

Before: [['University of Michigan', 'James Jones', 'phd'], ['University of Georgia', 'Anne Greene', 'ba'], ['University of Michigan', 'Frank Kimball', 'ma'], ['University of Florida', 'Nate Franklin', 'ms'], ['University of Georgia', 'Sara Dean', 'ms'], ['University of Georgia', 'Beth Johnson', 'bs']] 
After: [['University of Florida', 'Nate Franklin', 'ms'], ['University of Georgia', 'Anne Greene', 'ba'], ['University of Georgia', 'Sara Dean', 'ms'], ['University of Georgia', 'Beth Johnson', 'bs'], ['University of Michigan', 'James Jones', 'phd'], ['University of Michigan', 'Frank Kimball', 'ma']] 
相關問題