简体   繁体   中英

Python: How to sort a list of lists by the most common first element?

How do you sort a list of lists by the count of the first element? For example, if I had the following list below, I'd want the list to be sorted so that all the 'University of Georgia' entries come first, then the 'University of Michigan' entries, and then the 'University of Florida' entry.

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']]
from collections import Counter
c = Counter(item[0] for item in l)
print sorted(l, key = lambda x: -c[x[0]])

Output

[['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 version:

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

defaultdict version:

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

Getting solution from here: 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))

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM