2016-09-20 86 views
-3

我有這些列表:追加列表(IndexError:列表索引超出範圍)

n_crit = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 4, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 6, 0, 0], [0, 0, 0, 0, 0, 5]] 

crit = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3, 8], [94, 96, 7, 3.6, 5, 6]] 

和我有這些代碼:

DivMatrix = [] 
for x in range(len(crit)): 
    subList1 = [] 
    for y in range(len(crit[x])): 
     subList2 = [] 
     if (n_crit[2][x]>0): 
      for z in range(len(crit[x])): 
       subList2.append(crit[y][x] - crit[z][x]) 
     elif (n_crit[2][x]<0): 
      for z in range(len(crit[x])): 
       subList2.append(-(crit[y][x] - crit[z][x])) 
     subList1.append(subList2) 
    DivMatrix.append(subList1)  

現在我想用

n_crit = [[1, 2, 3, 4, 5], [0.23, 0.15, 0.15, 0.215, 0.255], [-1, -1, 1, 1, 1], [2, 6, 5, 4, 1], [4000, 0, 20, 0, 0], [0, 0, 40, 2, 0], [0, 1.5, 0, 0, 0]] 

crit = [[15000, 7, 60, 3, 3], [27000, 9, 120, 7, 7], [19000, 8.5, 90, 4, 5], [36000, 10, 140, 8, 7]] 

而是我收到此錯誤信息:另一對是列表的相同的代碼

subList2.append(-(crit[y][x] - crit[z][x])) 
IndexError: list index out of range 

我真的不知道什麼是錯,但我想要使用這個代碼對任何我想要的列表對。

+0

'len(暴擊)'!='len(n_crit)' –

+0

這兩個表都是不同的長度 –

回答

1

顯然列表的時間超出範圍引用列表元素時。

第一個例子,考慮名單的尺寸(儘量想列表爲矩陣的兩個維度,在列表中的每個元素是矩陣的行)

n_crit = 7x6 (6x5, if starts with 0) 
crit = 6x6 (5x5, if starts with 0) 

而在你的編程代碼:

x should in [0, rows of crit-1], that is [0, 5] 
y should in [0, cols of crit-1], that is [0, 5] 
z should in [0, cols of crit-1], that is [0, 5] 

所以每

crit[y][x], crit[z][x] are in 5x5 matrix, crit itself is 5x5, 

,這意味着它們是有效的。

爲了您的第二個例子

n_crit = 7x5 (6x4, if starts with 0) 
crit = 4x5 (3x4, if starts with 0) 
x should in [0,3] 
y should in [0,4] 
z should in [0,4] 
crit[y][x], crit[z][x] are in 4x3 matrix, while crit itself is 3x4 

顯然會提高外的範圍之外。

我相信你的輸入肯定有問題,你是否弄錯了第二個列表的行和列。理論上,當你對兩個矩陣A和B進行操作時,通常需要列出行(B)=行(B)的 ,例如矩陣乘法。所以檢查你的輸入。

0

在引發異常的Z值4,但n_crit是它是由造成4所以指數4(列表中的第5)不存在

相關問題