python中的计数器汇总 [英] Summing list of counters in python

查看:157
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆