访问键而不是索引上的字典元素时出现键错误

时间:2018-10-10 19:47:47

标签: python-3.x dictionary keyerror

我编写了下面的函数以在列表中找到总和等于目标的货币对:

def twoSum(nums, target):
    hash={}
    for i in nums:
        if i in hash.keys():
            continue
        hash[i]=0
    print(hash)
    for i in range(len(nums)):
        temp=target-nums[i]
        if (hash[temp]==1):
            return (nums.index(temp),i)
        else:
            hash[nums[i]]=1
            print(hash)

我已通过nums = [3,2,3]和target = 6。 执行此代码时,出现以下错误:

{3: 0, 2: 0}
{3: 1, 2: 0}
Traceback (most recent call last):
File "xyz\#1_two_sum.py", line 18, in <module>
print(twoSum(nums,target))
File "xyz\#1_two_sum.py", line 10, in twoSum
if (hash[temp]==1):
KeyError: 4

我想知道我在哪里犯错。

1 个答案:

答案 0 :(得分:1)

输入您的代码

def twoSum(nums, target):
    hash={}
    for i in nums:
        if i in hash.keys():
            continue
        hash[i]=0
    print(hash) # lineA
    for i in range(len(nums)): # lineB
        temp=target-nums[i]
        if (hash[temp]==1): # lineC
            return (nums.index(temp),i)
        else: # lineD
            hash[nums[i]]=1
            print(hash)

它执行如下:

  1. lineAhash{3: 0, 2: 0}
  2. 然后循环从lineB开始,第一个循环为i is 0,因此temp6-3,即3hash[3]0,不等于1,因此转到lineD
  3. 再次从lineB开始循环,第二个循环i is 1,所以temp6-2,即4,然后是{{1 }}执行lineC,给您错误:
  

如果(哈希[temp] == 1):

     

KeyError:4

实际上,我不太了解您获得配对的逻辑,请参阅下一个可以实现目标的功能,仅供参考:

test.py:

if hash[4]==1)

只需执行它,下一个输出将找到所有对:

  

[(3,3)]

     

[]

     

[(1,5),(2,4)]

     

[(1,5),(3,3),(2,4)]

     

[(-1,7)]