我正在做一个简单的任务:在 Python 中找到两个数组的交集。
我写的代码:
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
hash_2 = {}
for x in nums2:
if x in hash_2:
hash_2[x] = 1
else:
hash_2[x] = hash_2[x] + 1
intersection = []
for x in nums1:
if x in hash_2:
if hash_2[x] >0:
intersection.append(x)
hash_2[x] = hash_2[x] - 1
return intersection
print(intersect([],[1]))
我明白了:
line 14, in intersect
hash_2[x] = hash_2[x] + 1
KeyError: 1
我试过调试,但没有用。为什么 python 程序在字典本身为空时向 else 条件发送 1?
这是 Python 字典中的一些问题,您不应该在空字典中搜索吗?
最佳答案
x
中的值 1
不在 hash_2
中(因为 hash_2
为空),所以 else
分支被采用。由于 x
不在 hash_2
中,您会在尝试访问 hash_2[x]
时遇到 KeyError
。
看起来您希望您的测试是if x not in hash_2
。
关于python - 空字典 Python 中的 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48718962/