python - 空字典 Python 中的 KeyError

标签 python arrays algorithm dictionary data-structures

我正在做一个简单的任务:在 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/

相关文章:

python - 在python中使用selenium获取所有href链接

arrays - R - 基于另一个数组连接字符串元素

javascript - renameFiles - 获取文件名数组并根据它们在数组中出现的次数重命名它们

python - 如何有效地找到有向无环图中由k个节点组成的所有路径?

具有多个谓词的 C++11 算法

algorithm - 现代 X86 处理器如何实际计算乘法?

python - 从python中的迭代对象创建一个带有一组树的迭代对象

python - 替换 pandas 数据系列中的某些值?

python - 如何逐行搜索文件,然后将包含特定字符串的行复制到列表中?

c - 多维数组作为结构体成员的内存分配 C