据我了解,我知道何时调用 Counter
来隐藏 dict。此字典包含键的值为零将消失。
from collections import Counter
a = {"a": 1, "b": 5, "d": 0}
b = {"b": 1, "c": 2}
print Counter(a) + Counter(b)
如果我想保留我的 key ,怎么办?
这是我的预期结果:
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
最佳答案
您还可以使用 update()
Counter 的方法而不是 +
运算符,示例 -
>>> a = {"a": 1, "b": 5, "d": 0}
>>> b = {"b": 1, "c": 2}
>>> x = Counter(a)
>>> x.update(Counter(b))
>>> x
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
update()
函数添加计数而不是替换它们,并且它也不会删除零值。我们也可以先做Counter(b)
,再用Counter(a)
更新,Example -
>>> y = Counter(b)
>>> y.update(Counter(a))
>>> y
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})
关于python - 添加计数器时如何保留我的原始字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534546/