Python 2 IndexError:列表索引超出范围

时间:2016-07-01 14:10:59

标签: python

我正在尝试解决Project Euler Problem 15。

我在mainarray中放了一些数组。

我在第33行得到一个IndexError:list index超出范围但不知道为什么。有人能帮助我吗?

感谢。

这是我的代码:

def make_file(num_matrix):
    file = open("euler15.csv", "w")

    for a in num_matrix:
        for b in a:
            file.write(str(b) + ",")
        file.write("\n")
    file.close()

mainarray = []

act_cell_row = 1
act_cell_column = 1
summand_1 = 0
summand_2 = 1
x = 1
y = 0
for c in range(0,20):
    mainarray.append([])
for d in range(2,22):
    mainarray[0].append(d)
for e in range(3,22):
    mainarray[x].append(e)
    x += 1

for f in mainarray:
    for g in f:
        print "act_cell_column ", act_cell_column
        print "act_cell_row ", act_cell_row
        print "summand_2 ", summand_2
        print "summand_1 ", summand_1   
        akt_feld = (mainarray[summand_1][summand_2]) + (mainarray[summand_2][summand_1])
        mainarray[act_cell_row][act_cell_column] = akt_feld
        if y < 18:
            summand_2 += 1
            act_cell_column += 1
            y += 1
    summand_1 += 1
    summand_2 = 1
    act_cell_row += 1
    act_cell_column = 1

make_file(mainarray)
result = mainarray[19][19]
print "RESULT: ", result

1 个答案:

答案 0 :(得分:0)

要检查,发生错误时,您可以在akt_feld分配之前添加此代码:

try:
    _ = mainarray[summand_1][summand_2]
except IndexError:
    print("something wrong with this indexes", summand_1, summand_2)

或者只是致电mainarray[1][1]

In [7]: print(mainarray[1])
[3]

In [8]: print(mainarray[1][1])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-8-e23bb5ccbc5a> in <module>()
----> 1 print(mainarray[1][1])

IndexError: list index out of range