【问题标题】:KeyError in Empty Dictionary Python空字典Python中的KeyError
【发布时间】:2018-02-10 08:51:57
【问题描述】:

我正在做一个简单的任务:在 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 字典中不应该在空字典中搜索的问题吗?

【问题讨论】:

  • 这看起来像是 collections.Counter() 的作品。

标签: python arrays algorithm dictionary data-structures


【解决方案1】:

x1 中的值不在hash_2 中(因为hash_2 为空),所以采用else 分支。由于x 不在hash_2 中,你会得到一个KeyError 试图访问hash_2[x]

看起来你希望你的测试是if x not in hash_2

【讨论】:

    【解决方案2】:

    我不明白hash_2是什么意思,但是如果你想计算两个序列的交集,这里有一个解决方案:

    def intersection(seq1, seq2):
        result = list()
        for item in seq1:
            if item in seq2:
                result.append(item)
        return result
    
    def main():
        a = [10, 20, 30, 40, 'salam', 'bye', ['!', '*']]
        b = [10, 11, 23, 30, 'salam', 'not', ['!', '*']]
        print(intersection(a, b))
    
    main()
    

    【讨论】:

    • 你的解决方案是 O(n squared),使用哈希表使其 O(n) 以 O(n) 空间为代价
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    相关资源
    最近更新 更多