我正在尝试使用列表中的列表(其中的行和列的列表)创建值的“矩阵”。 像这样的东西:
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
首先,我创建一个无值列表列表:
columns = [None for _ in range(3)]
matrix_d = [columns] * 3
[None, None, None]
[None, None, None]
[None, None, None]
然后,当我想将行中的第一个元素的值更改为从0增长到第1行数时:
i = 0
for row in matrix:
row[0] = i
i += 1
我没有得到我想要的东西:
[2, None, None]
[2, None, None]
[2, None, None]
这很奇怪,但是随着for循环的每次迭代,每行的每个第一个元素都会更改其值。有人知道为什么会这样发生吗?
i = 0
for row in matrix:
row[0] = i
i += 1
print(matrix)
每个列表(行)的变化:
[[0, None, None], [0, None, None], [0, None, None]]
[[1, None, None], [1, None, None], [1, None, None]]
[[2, None, None], [2, None, None], [2, None, None]]
如何获得此结果?
[0, None, None]
[1, None, None]
[2, None, None]