python - 比较两个 collections.defaultdict 并删除相似的值

标签 python collections counter defaultdict

我有两个 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' 相同的值即使我想删除所有类似的。

最佳答案

从,d1d2Counter它们实现与集合不同的减法的对象。

From collections.Counter(emphasis mine):

Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements.



From set.difference or set - 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/

相关文章:

Java:使用什么数据结构来实现可预测的排序、无重复并维护自己的整数索引?

excel - 计数器帮助VBA

python:从收集计数器获取百分比

python - 如何在异步函数中并行化 for 循环并跟踪 for 循环执行状态?

python Tk 在我设置后保留标签文本

java - Python 等效于 java PBKDF2WithHmacSHA1

c# - 用于查找字符串属性以以下开头的所有项目的最快集合

python - 编程错误: can't adapt type 'account.account' - Odoo v8

excel - 从项目集合中调用项目

java - 在 java 中创建一个计数计时器(仅秒和毫秒)