列表索引超出列表和矩阵的范围

时间:2017-09-19 01:48:45

标签: python matrix

我是编程的初学者。我总是遇到矩阵的这个问题。请帮我纠正这个代码并理解这背后的概念。谢谢。

def new_matrix(matrix_size, center_num):
    c = matrix_size / 2
    if matrix_size % 2 != 0:
        p = matrix_size
        print("enter a valid size for matrix")
    else:
        matrix = [[0] * matrix_size for z in range(matrix_size)]
        for counting in range(center_num, (matrix_size ** 2) + center_num):
            for i in range(2, matrix_size+1):
                row = int(c)
                column = int(c)
                if (i % 2 == 0):
                    for k in range(1, i + 1):  # moving right
                        column += 1
                        matrix[column][row] = counting
                    for k in range(1, i + 1):  # moving up
                        row += 1
                        matrix[column][row] = counting
                else:
                    for k in range(1, i + 1):  # moving left
                        column -= 1
                        matrix[column][row] = counting
                    for k in range(1, i + 1):  # moving down
                        row -= 1
                        matrix[column][row] = counting
        print(matrix)


new_matrix(6, 2)

1 个答案:

答案 0 :(得分:-1)

此问题似乎是您的索引已关闭。 range(n)中的结束值为n-1,这意味着在i = matrix_size的for循环中,然后您尝试将列增加到此之外,您尝试将值分配给矩阵中的索引不存在。

您可以尝试修复循环,即将其减少一个,或者您可以执行以下操作,

try:
    <your code goes here>
except IndexError:
    pass

然后,当循环遇到索引错误时,它将跳过该索引并尝试下一个。最好修复代码!