Python附加Counter to Counter,就像Python字典更新一样

she*_*nzy 4 python counter dictionary python-3.x python-collections

我有2个计数器(来自集合的计数器),我想将一个附加到另一个,而第一个计数器的重叠键将被忽略.像dic.update(python词典更新)

例如:

from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
Run Code Online (Sandbox Code Playgroud)

所以类似(忽略第一个计数器的重叠键):

# a.update(b) 
Counter({'a':4, 'z':1, 'b':2, 'c':3})
Run Code Online (Sandbox Code Playgroud)

我想我总是可以将它转换成某种字典,然后将其转换回Counter,或使用条件.但我想知道是否有更好的选择,因为我在一个非常大的数据集上使用它.

Ara*_*Fey 9

Counter是一个dict子类,因此您可以显式调用dict.update并传递两个计数器作为参数:

a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)

dict.update(a, b)

print(a)
# Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})
Run Code Online (Sandbox Code Playgroud)

  • @sheldonzy当然.它就地修改了"a",所以它不必返回任何东西. (3认同)

Soh*_*oqi 5

你也可以使用 dict unpacking

from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
Counter({**a, **b})
Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})
Run Code Online (Sandbox Code Playgroud)