python计数器的汇总列表

问题描述 投票:24回答:2

我希望总结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'感到困惑?鉴于可以将计数器加在一起,为什么不能对它们求和?

python python-2.7 counter
2个回答
47
投票

sum函数具有可选的start参数,该参数默认为0。引用链接的页面:

sum

开始可迭代的项目从左到右并返回 总数

开始设置为(空)sum(iterable[, start])对象,以避免Counter

TypeError

0
投票

根据我的经验,此版本速度更快。这是O(log(n))

的上限
In [5]: sum(counter_list, Counter())
Out[5]: Counter({'b': 5, 'c': 4, 'a': 1})

global_counter = sum_counters(counter_list)

© www.soinside.com 2019 - 2024. All rights reserved.