Baz Baz - 1 year ago 111
Python Question

Sum of all counts in a collections.Counter

What is the best way of establishing the sum of all counts in a collections.Counter object?

I've tried:


but this gives 21 instead of 9?

Answer Source

The code you have adds up the keys (i.e. the unique values in the list: 1+2+3+4+5+6=21).

To add up the counts, use:

In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9

This idiom is mentioned in the documentation, under "Common patterns".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download