首页 > 解决方案 > 从没有循环的计数器列表中更新计数器?

问题描述

我有一个计数器列表:

from collections import Counter
counters = [
    Counter({"coach": 1, "says": 1, "play": 1, "basketball": 1}),
    Counter({"i": 2, "said": 1, "hate": 1, "basketball": 1}),
    Counter({"he": 1, "said": 1, "play": 1, "basketball": 1}),
]

我可以使用如下所示的循环组合它们,但我想避免循环。

all_ct = Counter()
for ct in counters:
    all_ct.update(ct)

使用reduce会报错:

all_ct = Counter()
reduce(all_ct.update, counters) 
>>> TypeError: update() takes from 1 to 2 positional arguments but 3 were given

有没有办法在不使用循环的情况下将计数器组合成一个计数器?

标签: pythonfunctional-programming

解决方案


你可以使用求和功能。

all_ct = sum(counters, Counter())

推荐阅读