如何合并多个defaultdict(Counter)?

2 投票
1 回答
4229 浏览
提问于 2025-04-17 22:03

如何合并多个 defaultdict(Counter)

假设我有两个 defaultdict(Counter),我尝试了以下方法,虽然成功了,但有没有其他方式可以实现合并呢?

>>> from collections import Counter, defaultdict
>>> x = {'a':Counter(['abc','def','abc']), 'b':Counter(['ghi', 'jkl'])}
>>> y = {'a':Counter(['abc','def','mno']), 'c':Counter(['lmn', 'jkl'])}
>>> z = x+y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> z = defaultdict(Counter)
>>> for i in x:
...     z[i].update(x[i])
... 
>>> for i in y:
...     z[i].update(y[i])
... 
>>> z
defaultdict(<class 'collections.Counter'>, {'a': Counter({'abc': 3, 'def': 2, 'mno': 1}), 'c': Counter({'jkl': 1, 'lmn': 1}), 'b': Counter({'jkl': 1, 'ghi': 1})})

1 个回答

5

这看起来还不错,虽然有点像是在追求代码的简洁性:

{k:(x.get(k,Counter()) + y.get(k,Counter())) for k in (x.keys()+y.keys())}
Out[23]: 
{'a': Counter({'abc': 3, 'def': 2, 'mno': 1}),
 'b': Counter({'jkl': 1, 'ghi': 1}),
 'c': Counter({'jkl': 1, 'lmn': 1})}

如果你想保持 defaultdict 的输出格式,可以用一个循环和 itertools.chain 来简化代码:

z = defaultdict(Counter)

for k,v in chain(x.iteritems(), y.iteritems()):
    z[k].update(v)

撰写回答