python中的计数器汇总 [英] Summing list of counters in python
问题描述
我正在寻求汇总python中的计数器列表。例如,求和:
I am looking to sum a list of counters in python. For example to sum:
counter_list = [Counter({"a":1, "b":2}), Counter({"b":3, "c":4})]
给出 Counter({'b':5,'c':4,'a':1})
我可以得到以下代码进行求和:
I can get the following code to do the summation:
counter_master = Counter()
for element in counter_list:
counter_master = counter_master + element
但是我对为什么 counter_master = sum感到困惑(counter_list)
导致错误 TypeError:+不支持的操作数类型: int和 Counter
?既然可以将计数器加在一起,为什么不能将它们相加?
But I am confused as to why counter_master = sum(counter_list)
results in the error TypeError: unsupported operand type(s) for +: 'int' and 'Counter'
? Given it is possible to add counters together, why is it not possible to sum them?
推荐答案
sum
函数具有可选的 start 参数,默认为0。引用链接页面:
The sum
function has the optional start argument which defaults to 0. Quoting the linked page:
sum(iterable [,start])
总和 start 和 iterable 的项目从左到右,并返回
总数
Sums start and the items of an iterable from left to right and returns the total
将 start 设置为(空)计数器
对象,以避免发生 TypeError
:
Set start to (empty) Counter
object to avoid the TypeError
:
In [5]: sum(counter_list, Counter())
Out[5]: Counter({'b': 5, 'c': 4, 'a': 1})
这篇关于python中的计数器汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!