2014-02-27 73 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']] 
相关问题