2015-07-21 62 views
1

我試圖添加列表l作爲不同的字典值d鍵。對於數組a,有[6,12,18,24,30]我試圖讓字典d包含以下鍵值對:添加列表到字典錯誤的輸出

d[6] = [0, 0, 0.....0] 
d[12] = [6, 0, 0, ..0] 
d[18] = [6, 12, 0, ...0] 
d[24] = [6, 12, 18, 0, ..0] 

哪裏有在上述各表的59元。

我使用下面的代碼要做到這一點,但我對關鍵24輸出是:

{24: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 12, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 18, 12, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} 

我想明白的地方,我錯了。

d = {} 
l = [] 
a =numpy.array([6,12,18,24,30]) 
for x, value in numpy.ndenumerate(a): 
    months_to_maturity = value 
    for i in range(6, 354, 6): 
     if i <= months_to_maturity: 
      l.append(months_to_maturity - i) 
     else: 
      l.append(0) 

    d[months_to_maturity] = l 
+0

您是否收到錯誤?與實際產出相比,您的預期產出是多少? – Claris

+1

@Claris我在問題中寫了什麼樣的輸出以及我想要什麼。我說我得到了錯誤的輸出,並沒有提到發生錯誤。 – user131983

回答

5

你總是追加到同一個列表。因此,所有字典值最終都指向相同的列表。您想每次追加到不同的列表:

d = {} 
a = numpy.array([6, 12, 18, 24, 30]) 
for months_to_maturity in a: 
    l = [] 
    for i in range(6, 354, 6): 
     if i <= months_to_maturity: 
      l.append(months_to_maturity - i) 
     else: 
      l.append(0) 

    d[months_to_maturity] = l