2017-03-24 88 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})

相關問題