从计数器列表更新计数器而不循环? [英] Update a counter from a list of counters without a loop?
本文介绍了从计数器列表更新计数器而不循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个柜台清单:
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}),
]
我可以使用如下所示的循环来组合它们,但我想避免循环.
I can combine them using a loop as shown below, but I'd like to avoid the loop.
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
有没有一种方法可以在不使用循环的情况下将计数器合并为一个计数器?
Is there a way to combine the counters into a single counter without using a loop?
推荐答案
您需要将update()替换为reduce可以使用的形式:
You need to replace update() with a form that reduce can use:
def static_update(x, y):
x.update(y)
return x
all_ct = Counter()
functools.reduce(static_update, counters)
这篇关于从计数器列表更新计数器而不循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文