在 python 中更新二维数组

Updating 2D array in python

    size = 10
    table = [[0] * size] * size
    for iter in range(size):
        table[iter][iter] = 9

    for iter in range(size):
        print(table[iter])

我试图将所有对角线元素设为 9,但它却将所有元素设为 9。

尝试使用嵌套列表理解来初始化 table:

size = 10
table = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size):
    table[i][i] = 9
for row in table:
  print(row)

输出:

[9, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 9, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 9, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 9, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 9, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 9, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 9, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 9]