Python: How to sort a list of lists by the most common first element?
list, python, sorting
Solution
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]])
Problem
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']] ```