2016-09-20 92 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)不存在

相关问题