我希望总结python中的计数器列表。例如求和:
counter_list = [Counter({"a":1, "b":2}), Counter({"b":3, "c":4})]
给出Counter({'b': 5, 'c': 4, 'a': 1})
我可以得到以下代码进行求和:
counter_master = Counter()
for element in counter_list:
counter_master = counter_master + element
但是我对counter_master = sum(counter_list)
为什么导致错误TypeError: unsupported operand type(s) for +: 'int' and 'Counter'
感到困惑?鉴于可以将计数器加在一起,为什么不能对它们求和?
sum
函数具有可选的start参数,该参数默认为0。引用链接的页面:
sum
和开始和可迭代的项目从左到右并返回 总数
将开始设置为(空)sum(iterable[, start])
对象,以避免Counter
:
TypeError
根据我的经验,此版本速度更快。这是O(log(n))
的上限In [5]: sum(counter_list, Counter())
Out[5]: Counter({'b': 5, 'c': 4, 'a': 1})
global_counter = sum_counters(counter_list)