6

I have a counter from the collections module. What is the best way of summing all of the counts?

For example, I have:

 my_counter = Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})

and would like to get the value 7 returned. As far as I can tell, the function sum is for adding multiple counters together.

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
kyrenia
  • 5,431
  • 9
  • 63
  • 93
  • if you had the source of the counter (e.g. `my_counter = Counter(source)`), you could just do `len(source)` – acushner Sep 10 '15 at 22:10

4 Answers4

10

Since your question is about Python 2.7, you should use something like this

sum(my_counter.itervalues())

which on Python 3.x is effectively equivalent to

sum(my_counter.values())

In both cases you evaluate the sum lazily and avoid expensive intermediate data structures. Beware of using the Python 3.x variant on Py 2.x, because in the latter case my_counter.values() calculates an entire list of counts and stores it in memory before calculating the sum.

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
4
>>> from collections import Counter
>>> sum(Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}).values())
7

Common patterns for working with Counter objects: sum(c.values())
# total of all counts

Source: https://docs.python.org/2/library/collections.html

Joe Young
  • 5,749
  • 3
  • 28
  • 27
0
c = Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
len( list(c.elements()) )
m.antkowicz
  • 13,268
  • 18
  • 37
0

from here:

from collections import Counter
c = Counter([1,2,3,4,5,1,2,1,6])
sum(c.values())
Gigi
  • 587
  • 5
  • 12