>>> from collections import Counter
>>> x = Counter([('a'), ('a', 'bc'), ('a', 'bc'), ('xyz', 'hooli')])
>>> y = Counter([('a'), ('a'), ('a'), ('asd', 'asd')])
>>> z = Counter([('a'), ('a'), ('a'), ('a'), ('a', 'bc')])
>>> x | y | z
Counter({'a': 4, ('a', 'bc'): 2, ('asd', 'asd'): 1, ('xyz', 'hooli'): 1})
但是,如果我有一个Counters列表作为函数的输入,我如何获得联合?
我必须循环每个计数器,然后执行并集吗?例如。
>>> xyz = [x,y,z]
>>> def counter_union(counters):
... union = Counter()
... for c in counters:
... union = union | c
... return union
...
>>> counter_union(xyz)
Counter({'a': 4, ('a', 'bc'): 2, ('asd', 'asd'): 1, ('xyz', 'hooli'): 1})