我有两个 collections.defaultdict
并尝试从 d1
中删除值也在 d2
.
from collections import Counter, defaultdict
d1 = Counter({'hi': 22, 'bye': 55, 'ok': 33})
d2 = Counter({'hi': 10, 'hello': 233, 'nvm': 96})
理想结果:d3 = set()
d3 = ({'bye':55, 'ok':33})
到目前为止,我已经尝试过:d3 = set()
d3 = d1 - d2
print(d3)
Counter({'bye': 55, 'ok': 33, 'hi': 12})
但这保持与 'hi'
相同的值即使我想删除所有类似的。
最佳答案
从,d1
和 d2
是 Counter
它们实现与集合不同的减法的对象。
From
collections.Counter
(emphasis mine):Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements.
From
set.difference
orset - other
:Return a new set with elements in the set that are not in the others.
也就是说,您可以使用Counter.keys
并使用difference
就像套。keys = d1.keys() - d2.keys() # keys = {'bye', 'ok'} out = {k: d1[k] for k in keys} # out = {'bye': 55, 'ok': 33}
关于python - 比较两个 collections.defaultdict 并删除相似的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69648693/