Python: how to sort the number of items in a list?

In Python, I have a list of elements like:

mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]

And I would like to output something like:

a (4)
b (3)
d (3)
c (2)
e (1)

How can I display the score and leaderboard in the list? I'm not too worried about efficiency, and it all works :)

Thank!

+5
source share
2 answers
from collections import defaultdict

def leaders(xs, top=10):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]

Thus, this function uses defaultdictto count the amount of each record in our list. Then we take each pair of records and its account and sort it in descending order of the account. Then we take the topnumber of records and return them.

So now we can say

>>> xs = list("jkl;fpfmklmcvuioqwerklmwqpmksdvjioh0-45mkofwk903rmiok0fmdfjsd")
>>> print leaders(xs)
[('k', 7), ('m', 7), ('f', 5), ('o', 4), ('0', 3), ('d', 3), ('i', 3), ('j', 3), ('l', 3), ('w', 3)]
+5
source

Two-line:

for count, elem in sorted(((mylist.count(e), e) for e in set(mylist)), reverse=True):
    print '%s (%d)' % (elem, count)
+5
source

All Articles