小编izz*_*zza的帖子

如何在 Python 中制作二维列表(没有 numpy)?

这可能是重复的问题,但我仍然对此感到好奇。

我想在没有 numpy 的情况下用 Python 制作二维列表。所以我列出了清单。这是我的代码:

myList = [None] * 3
print('myList :', myList)
myMatrix = [myList] * 3
#myMatrix = [[None, None, None], [None, None, None], [None, None, None]]
print('myMatrix', myMatrix)
for i in range (0,3):
    for j in range (0, 3):
        myMatrix[i][j] = i+j
    print('myMatrix[',i,'] : ', myMatrix[i])

print(myMatrix)
print(myMatrix[0])
print(myMatrix[1])
print(myMatrix[2])
Run Code Online (Sandbox Code Playgroud)

我知道声明:

myMatrix = [myList] * 3
Run Code Online (Sandbox Code Playgroud)

使代码无法按预期工作,这是因为 list 是可变对象,这意味着 myMatrix[0]、myMatrix[1]、myMatrix[2] 将引用同一个对象。对它们中的任何一个进行更改都意味着对所有这些更改,这不是我在代码中所期望的。这是我的代码的意外输出:

('myList :', [None, None, None])
('myMatrix', [[None, None, None], [None, None, None], [None, None, None]]) …
Run Code Online (Sandbox Code Playgroud)

python list mutable matrix

1
推荐指数
1
解决办法
2万
查看次数

标签 统计

list ×1

matrix ×1

mutable ×1

python ×1