在Q3初始化二维数组后重新赋值出现了以下的问题:
def matrix_gen(m, n):
a = [0] * n
matrix = []
for i in range(m):
matrix.append(a)
return matrix
或者在按以下方式初始化数组:
matrix = [[0] * 5] * 3
当在对这个数组重新赋值时,会出现:
In: matrix[0][0] = 1
Out: [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
与我们的理想结果
Out: [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
不一致
在python tutor中进行代码可视化,我们可以看到:

我们以下图方式形成数组:

当我们修改数组时,由于list的immutable特性,实际上0~2位指向同一个list,该0位的时候实际上就把1,2位的数组也改了

故会出现这种问题。
我们采用另外一种方式即可:
matrix = [[0] * 5 for _ in range(3)]
在python tutor中:

再次修改数组便不会出现上述问题。
网友评论