Skip to main content
 首页 » 编程设计

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

2025年05月04日27傻小

<分区>

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

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

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 

使代码无法按我的预期工作,这是因为列表是可变对象,这意味着 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,但我想先在没有 numpy 的情况下解决这个问题。