tags:

views:

88

answers:

2

In Python, I've got a list of items like:

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

And I'd like to output something like:

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

How can I output a count and leaderboard of items in a list? I'm not too bothered about efficiency, just any way that works :)

Thanks!

+2  A: 
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]

So this function uses a defaultdict to count the number of each entry in our list. We then take each pair of the entry and its count and sort it in descending order according to the count. We then take the top number of entries and return that.

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)]
Eli Courtwright
Perfect. Thank you
AP257
+2  A: 

A two-liner:

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