Summing list of counters in python

一个人想着一个人 提交于 2019-12-09 14:29:22

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30003466/summing-list-of-counters-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!