2017-03-24 93 views
0

我在我正在使用的函数中使用类似的方法。当我尝试这样做时,为什么会出现重大错误?将多个值添加到字典中的一个键与for循环

def trial(): 
    adict={} 
    for x in [1,2,3]: 
      for y in [1,2]: 
       adict[y] += x 
print(adict) 
+0

您尝试添加的东西'adict [Y]'和'adict [Y] + = x',但'adict [ y]'在第一次尝试访问密钥时未定义。 – Matthias

回答

1

adict从空开始。您不能将整数添加到尚不存在的值中。

+0

详细说明一下,你就地的adict [y] + = x'行是问题所在。第一遍没有什么“就地”了。 – blacksite

0

当您第一次使用它时,没有将值分配给adict[y]

def trial(): 
    adict={} 
    for x in [1,2,3]: 
      for y in [1,2]: 
       if y in adict: # Check if we have y in adict or not 
        adict[y] += x 
       else: # If not, set it to x 
        adict[y] = x 
    print(adict) 

输出:

>>> trial() 
{1: 6, 2: 6} 
+0

不,“adict [y]'不是'None',它不存在。这是两件不同的事情。 – Matthias

+0

@Matthias谢谢,更新。 – Yang

0

你应该修改这样的youre代码:

def trial(): 
    adict={0,0,0} 
    for x in [1,2,3]: 
     for y in [1,2]: 
      adict[y] += x 
print(adict) 

“adict” 会没有入口。所以adict [1]失败,因为它正在访问一个不存在的变量。

1

您没有初始化每个密钥的adict。您可以使用defaultdict来解决这个问题:

from collections import defaultdict 
def trial(): 
    adict=defaultdict(int) 
    for x in [1,2,3]: 
     for y in [1,2]: 
      adict[y] += x 
    print(adict) 
trial() 

结果是defaultdict(<class 'int'>, {1: 6, 2: 6})

相关问题