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

标签 python python-3.x dictionary counter 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)

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

# a.update(b) 
Counter({'a':4, 'z':1, 'b':2, 'c':3})

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

最佳答案

Counter is a dict subclass ,因此您可以显式调用 dict.update(而不是 Counter.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})

关于Python 将 Counter 附加到 Counter,就像 Python 字典更新一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49155472/

相关文章:

python - 在 Python 2.7.2 中设置端口以与 Arduino Uno 一起使用

python - 正则表达式两组匹配所有内容直到模式

python - 声明子类而不传递 self

python - 当查询具有动态生成/可变长度参数列表时防止 SQL 注入(inject)

c# - 查询嵌套字典

自动弹出窗口中的字典建议

Ruby:将一组键映射到值速记

Python/Seaborn : What does the inside horizontal distribution of the data-points means or is it random?

python - 文本(python)-如何在简单的文本对象中添加点击事件?

python - 在 Python 源文件中重命名变量和方法名