Python:如何按最常见的第一个元素对列表列表进行排序?

时间:2014-02-27 15:51:32

标签: python list sorting

如何按第一个元素的计数对列表列表进行排序?例如,如果我在下面列出了以下列表,我希望对列表进行排序,以便所有“乔治亚大学”的条目首先出现,然后是“密歇根大学”条目,然后是“佛罗里达大学”。条目。

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']]

2 个答案:

答案 0 :(得分: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']]

Vanilla dict版本:

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]])

答案 1 :(得分:-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']]