gpt4 book ai didi

python - python中计数器的总和列表

转载 作者:IT老高 更新时间:2023-10-28 21:08:08 28 4
gpt4 key购买 nike

我希望在 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(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total

start 设置为(空)Counter 对象以避免 TypeError:

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

关于python - python中计数器的总和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003466/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com