python初始为0的计数器,python中的计数器汇总

本文探讨了在Python中如何对Counter对象进行相加操作。通过示例展示了使用`+`运算符将Counter对象组合以及使用内置`sum`函数时遇到的TypeError错误。解决方法是利用`sum`函数的`start`参数,将其设置为空Counter对象,从而避免错误并正确地合并Counter列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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})]

to give 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

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?

解决方案

The sum function has the optional start argument which defaults to 0. Quoting the linked page:

sum(iterable[, start])

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

the total

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})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值