9

I have been researching this issue for a while, for solving 'combining' multiple Counter().object or dicts; But still can`t work it done. And I found two reference below:

For example I have many 'Counter Type' variable name with order [1 to 100]:

Name:counter_1 Value:Counter({'a':1, 'b':2, 'c':3})
Name:counter_2 Value:Counter({'b':5, 'c':19, f:17})
Name:counter_3 Value:Counter({'a':11, 'b':22, 'c':33, 'd':97})
...
Name:counter_100 Value:Counter({'c':55, 'd':22, 'e':63, 'f':21})

If I add each of one manually counter_1 + counter_2 + ... + counter_3, it will make me insane.

Is there more elegant or easier way to sum() it all?

Thanks a million!

Community
  • 1
  • 1
Kudos
  • 99
  • 1
  • 3

1 Answers1

10

Just use the built-in function sum(), and give it an appropriate starting value of an empty Counter.

>>> import collections
>>> c1 = collections.Counter({'a':1, 'b':2, 'c':3})
>>> c2 = collections.Counter({'b':5, 'c':19, 'f':17})
>>> sum((c1, c2), collections.Counter())
Counter({'c': 22, 'f': 17, 'b': 7, 'a': 1})
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • what if I have to sum from c1 to c100? tks – Kudos May 20 '16 at 03:13
  • You put them all into a `list`. You should be doing that already. Do you really have separate variables `counter_1` through `counter_100`? – TigerhawkT3 May 20 '16 at 03:21
  • Yes. I tried something like(but Type Error) `sum(local()['counter_'+ str(i) for i in (1,100)], Counter())`. and I am also new in python. – Kudos May 20 '16 at 03:26
  • Your first step should be avoiding making 100 separate named variables in the first place, and as TigerhawkT3 says, use a list (or a dictionary, depending on how much you care about the number). – DSM May 20 '16 at 03:34
  • Another question: how can I declare a `Counter Type` variable without any value? (When I consider avoiding making 100 separate named) – Kudos May 20 '16 at 03:43
  • I tried`Test = Counter()`. Successful. Sorry for bothering – Kudos May 20 '16 at 03:48