pomber
pomber

Reputation: 23980

Counter most_common elements as a generator

I'm using a collections.Counter object. I want to get the most common elements one by one but the most_common method gives me the whole list of elements.
Is there any way to get this list as a generator?

Upvotes: 3

Views: 2116

Answers (1)

martineau
martineau

Reputation: 123463

You could simply wrap collection.Counter.most_common() in a generator function like this:

from collections import Counter

def most_common(iterable, n=None):
    return iter(Counter(iterable).most_common() if n is None else
                Counter(iterable).most_common(n))

for item in most_common('Mississippi', 3):
    print item

Note: While it appears that passing None to collection.Counter.most_common() is the same as passing nothing to it (a common Python idiom), the current documentation does not actually say that, so I have decided to err on the side of caution and use an .. if .. else .. conditional expression to only pass it n when it's not None, however its docstring does explicitly say "If n is None, then list all element counts".

If this slight discrepancy doesn't worry you, the above could be shortened to just:

def most_common(iterable, n=None):
    return iter(Counter(iterable).most_common(n))

Which is so short, you might just want to code iter() around any Counter.most_common() calls you have to avoid the overhead of calling an extra wrapper-function.

Regardless, the output should look like this:

('i', 4)
('s', 4)
('p', 2)

Upvotes: 1

Related Questions