许多柜台的联盟 [英] Union of many Counters
问题描述
(在可读性和效率方面)找到计数器?
What's the best way (in terms of readability and efficiency) of finding the union of a list of Counters?
例如,我的列表可能像这样:
For example, my list might look like this:
counters = [Counter({'a': 6, 'b': 3, 'c': 1}),
Counter({'a': 2, 'b': 5}),
Counter({'a': 4, 'b': 4}),
...]
我想计算联合,即 counters [0] |柜台[1] |柜台[2] | ...
。
一种方法是:
def counter_union(iterable):
return functools.reduce(operator.or_, iterable, Counter())
有更好的方法吗?
推荐答案
好的,Python程序员什么时候做的?害怕容易循环?
Goodness, when did Python programmers become afraid of easy loops? LOL.
result = Counter()
for c in counters:
result |= c
在现实生活中,确实没有奖品可以将内容压缩成理论上尽可能少的字符。好吧,是的,Perl中有,但Python中没有;-)
There really aren't prizes in real life for squashing things into as few characters as theoretically possible. Well, ya, there are in Perl, but not in Python ;-)
稍后:根据user2357112的评论,从Python 3.3开始,以上代码将就地执行合并成结果
。也就是说,结果
是真正可重用的,可能在每次迭代中都变得更大。
Later: pursuant to user2357112's comment, starting with Python 3.3 the code above will do "in place" unions into result
. That is, result
is truly reused, possibly growing larger on each iteration.
任何
counters[0] | counters[1] | counters[2] | ...
相反,当下一个部分结果是计算的。这可能会或可能不会慢很多。
instead, the entire partial result so far keeps getting thrown away when the next partial result is computed. That may - or may not - be a lot slower.
这篇关于许多柜台的联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!