【发布时间】:2020-03-20 17:24:15
【问题描述】:
我想检查两个字典的交集。如果我这样做,我会得到我所期望的:
dict1 = {'x':1, 'y':2, 'z':3}
dict2 = {'x':1, 'y':2, 'z':4}
set(dict1.items()).intersection(dict2.items())
>> {('x', 1), ('y', 2)}
但是,如果字典中的项目 是不可散列的,则会出现错误。
dict1 = {'x':{1,2}, 'y':{2,3}, 'z':3}
dict2 = {'x':{1,3}, 'y':{2,4}, 'z':4}
TypeError Traceback (most recent call
last)
<ipython-input-56-33fdb931ef54> in <module>
----> 1 set(dict1.items()).intersection(dict2.items())
TypeError: unhashable type: 'set'
当然,对于元组和列表,我也会遇到同样的错误,因为它们也不是可散列的。
是否有解决方法或现有类可用于检查不可散列字典值的交集?
【问题讨论】:
-
x y 和 z 代表某种点?
-
不,这只是代表性数据。实际情况完全不同,但没关系,对吧?
-
@Prune 您链接到的问题不是针对不可散列的 dict 值,这是 OP 特别想要解决的问题。
-
接受的答案是针对可散列项;其他答案处理不可散列的。
-
@Prune 我明白了。我没有注意到解决不可散列问题的另一个答案,但这是一个相当糟糕的答案,因为当适当的解决方案应该在线性时间内完成时,它的时间复杂度会花费 O(n ^ 2)。跨度>
标签: python dictionary intersection hashset