Thanos Smar - 2 months ago 8

Python Question

I have these lists:

`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]]

and i have these code:

`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)

Now I want to use the same code for another pair of lists that are:

`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]]

But instead I get this error message:

`subList2.append(-(crit[y][x] - crit[z][x]))`

IndexError: list index out of range

I really don't know what is wrong but I want to use this code for any pair of lists I want.

Answer

Apparently it was caused by out-of-range when referring list element.

For the first example, consider the dimensions of the list (try to think the list as two dimensions of matrix, each element in list is a row in matrix)

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

And in your programming code:

```
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]
```

So every

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

which means they are valid.

For your second example

```
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
```

apparently will raise out-of-range exception.

I believe there must something wrong with your input, did you mistake the rows and columns of your second list.

In theory, when you do operation on two matrix, A and B, often it requires that cols(A)=rows(B), e.g., matrix multiplication. So check your input.

Source (Stackoverflow)

Comments