如何在Python中创建二维列表(没有numpy)? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

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

我想在没有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])

我知道声明:

myMatrix = [myList] * 3

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

('myList :', [None, None, None])
('myMatrix', [[None, None, None], [None, None, None], [None, None, None]])
('myMatrix[', 0, '] : ', [0, 1, 2])
('myMatrix[', 1, '] : ', [1, 2, 3])
('myMatrix[', 2, '] : ', [2, 3, 4])
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]

我找到的唯一解决方案是,不应该声明myMatrix = [myList] * 3,而应该写:

myMatrix = [[None, None, None], [None, None, None], [None, None, None]]

这将使代码按照我预期的方式工作(程序的输出):

('myMatrix', [[None, None, None], [None, None, None], [None, None, None]])
('myMatrix[', 0, '] : ', [0, 1, 2])
('myMatrix[', 1, '] : ', [1, 2, 3])
('myMatrix[', 2, '] : ', [2, 3, 4])
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]

但它不是定义NxN矩阵的有效方法,特别是如果N是一个大数字。

Python是否有一种使用列表列表定义NxN矩阵的有效方法?

我对C / C ++比较熟悉,所以这个问题真的让我烦恼。一些答案会建议我使用numpy,但此时我想从头开始学习基本的Python(不导入任何库)。当我使用C / C ++时,我可以轻松地使用这个二维数组,而无需导入任何库。当我刚刚使用Python时,要求我使用numpy,就像我刚刚接触C时要求我使用STL一样。

当然我稍后会学习numpy,但是我想首先解决这个问题。

python list matrix mutable
2个回答
3
投票

构建它的最直接的方法是这样的:

list_of_lists = []
for row in range(rows):
    inner_list = []
    for col in range(cols):
        inner_list.append(None)
    list_of_lists.append(inner_list)

或者列表理解:

list_of_lists = [[None for col in range(cols)] for row in range(rows)]

这两种方式是等价的。


1
投票

要创建最初填充myListNone,您可以这样做:

N = 3
myList = [[None] * N for i in range(N)]

print(myList)

这使:

[[None, None, None], [None, None, None], [None, None, None]

然后,如果要更新每个单元格,只需遍历行和列,其中row是矩阵中行的索引,col是矩阵中列的索引。然后你可以相应地更新每个my_List[row][col]单元格:

for row in range(N):
    for col in range(N):
        myList[row][col] = row + col

print(myList)

哪些输出:

[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
© www.soinside.com 2019 - 2024. All rights reserved.