【问题标题】:Appending lists according to a pair of lists (IndexError: list index out of range)根据一对列表附加列表(IndexError:列表索引超出范围)
【发布时间】:2017-01-28 18:09:38
【问题描述】:

我有这些清单:

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

我真的不知道出了什么问题,但我想将此代码用于我想要的任何一对列表。

【问题讨论】:

  • len(crit) != len(n_crit)
  • 两个列表的长度不同

标签: python list for-loop append


【解决方案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 进行运算时,通常需要 cols(A)=rows(B),例如矩阵乘法。所以请检查您的输入。

【讨论】:

    【解决方案2】:

    在引发异常时,您的 Z 值为 4,但 n_crit 是 4 的列表,因此索引 4(列表中的第 5 个)不存在

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-31
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多