简体   繁体   English

空字典Python中的KeyError

[英]KeyError in Empty Dictionary Python

I am doing a simple task: find intersection of two arrays in Python. 我正在做一个简单的任务:在Python中找到两个数组的交集。

I wrote the code: 我写了代码:

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]))

I get : 我得到:

    line 14, in intersect
    hash_2[x] =  hash_2[x] + 1
KeyError: 1

I tried debugging but it is not helping. 我尝试调试,但没有帮助。 Why is the python program sending 1 to else condition when the dictionary itself is empty? 当字典本身为空时,为什么python程序将1发送到else条件?

Is this some issue in Python's dictionary that you should not search in empty dictionaries? 这是Python字典中的某个问题,您不应该在空字典中进行搜索吗?

The value in x , 1 , isn't in hash_2 (since hash_2 is empty), so the else branch is taken. x1的值不在hash_2 (因为hash_2为空),所以采用else分支。 And since x isn't in hash_2 , you get a KeyError trying to access hash_2[x] . 而且,由于x不在hash_2 ,你会得到一个KeyError试图访问hash_2[x]

It looks like you want your test to be if x not in hash_2 . if x not in hash_2您似乎希望您的测试成为。

I don't get the point of hash_2 and what it is, But if you want to calculate the intersection of two sequences here is a solution: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM