问题出在初始化步骤上.
for i in range (0,m):
matrix[i] = columns
此代码实际上使矩阵的每一行都引用相同的列对象.如果任何列中的任何项目发生更改 – 每隔一列都会更改:
>>> for i in range (0,m):
... matrix[i] = columns
...
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]
您可以在嵌套循环中初始化矩阵,如下所示:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
或者,使用列表理解在单行中:
matrix = [[0 for j in range(n)] for i in range(m)]
要么:
matrix = [x[:] for x in [[0]*n]*m]
也可以看看:
希望有所帮助.