循环不应该向矩阵追加一个,然后两个,然后三个数字吗?

Shouldn't the loop append one, then two, then three numbers to the matrix?

def matrixInput():
  matrix=[]
  print("Enter the elements row-wise: ")
  for i in range(0,3):
    a = []
    for j in range(0,3):
      a.append(int(input()))
      matrix.append(a) #this line should have been back one tab, this was a typo mistake...however left like this, the code is running in an unexpected way
  print((matrix))


print(matrixInput())

#this code's output:
Enter the elements row-wise: 
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [7, 8, 9], [7, 8, 9], [7, 8, 9]]
None

#shouldn't it print:
#[[1],[1,2],[1,2,3],[4],[4,5],[4,5,6],[7],[7,8][7,8,9]]...??

所以我是 UNI 第一年的新开发人员。在完成实验时,我犯了一个拼写错误,导致了奇怪的输出。我修正了这个错误,但我仍然对错字的结果感兴趣。它产生了意想不到的结果。我已经考虑了好几天了,只是想不通为什么结果与我的预期不同。

#我错过了什么???

将数组的变量视为存储位置,类似于引用。当您将数组“a”添加到矩阵时,矩阵数组只记住 a 的地址,当您将数据附加到“a”并更改“a”时,矩阵中引用“a”的先前索引实际上发生了变化。在第一个循环中,每次迭代都会重置数组“a”的内存,因此数组“a”中只有3个副本保存在矩阵中。

假设当您设置 a = [] 时,我们有一个新的内存位置用于 a,我们共有 a、a2 和 a3。循环结束的矩阵数组有值[a,a,a,a2,a2,a2,a3,a3,a3],因为你打印所有迭代后的最终结果,每个a,a2,a3的值参考到会是一样的。

如果您觉得难以理解,请尝试运行这段代码

matrix = []
a = []
a.append(2)
matrix.append(a)   # matrix has [a]   a = [2]
print(matrix)      # matrix prints as [2]
a.append(3)
matrix.append(a)   # matrix has [a,a] a = [2,3]
print(matrix)      # matrix prints as [[2,3],[2,3]] instead of [[2],[2,3]], because matrix only knows [a,a] and a is [2,3] when this line is called