如何用循环对多个 collections.Counter() 对象的内容求和?
How to sum() the contents of multiple collections.Counter() objects with loop?
这个问题我研究了一段时间,
用于解决 'combining' multiple Counter().object 或 dicts;但仍然无法完成。
我在下面找到了两个参考:
- Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
- Summing the contents of two collections.Counter() objects
例如,我有很多'Counter Type'变量名,顺序为[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})
如果我手动添加每一个 counter_1 + counter_2 + ... + counter_3
,我会发疯的。
是否有更优雅或更简单的方法来 sum() 全部?
百万感谢!
只需使用内置函数sum()
,并给它一个适当的空值起始值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})
这个问题我研究了一段时间,
用于解决 'combining' multiple Counter().object 或 dicts;但仍然无法完成。
我在下面找到了两个参考:
- Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
- Summing the contents of two collections.Counter() objects
例如,我有很多'Counter Type'变量名,顺序为[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})
如果我手动添加每一个 counter_1 + counter_2 + ... + counter_3
,我会发疯的。
是否有更优雅或更简单的方法来 sum() 全部?
百万感谢!
只需使用内置函数sum()
,并给它一个适当的空值起始值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})