Skip to main content
 首页 » 编程设计

python之python中嵌套列表的意外行为

2025年05月04日14yxwkf

我有一个名为 basic 的嵌套列表,我想更改其中的一个条目。我假设了以下行为:

expected = [ [9],[0] ] 
unexpected = [ [9],[9] ] 
basic = [ [0],[0] ] 
basic[0][0] = 9 
print(basic == expected) # this is true 

然而,稍作修改就会产生令人惊讶的输出:

l = [0] 
modified = [ l, l ] 
modified[0][0] = 9 
print(modified == expected) # this is false 
print(modified == unexpected) # this is true 

如果您的列表是用第二种方式定义的,赋值会将整列设置为 9。

这是设计使然的行为吗?如果是这样,为什么?我在文档中找不到任何相关内容。

请您参考如下方法:

在你的第一个例子中:

basic = [ [0],[0] ] 

您已经创建了一个包含两个不同列表对象的列表对象。通过id() or identity 可以看出它们是不同的对象:

assert id(basic[0]) != id(basic[1]) 
 
assert basic[0] is not basic[1] 

在你的第二个例子中:

l = [0] 
modified = [ l, l ] 

您已将同一个列表对象放入另一个列表两次。两个列表索引都引用同一个对象:

assert id(basic[0]) == id(basic[1]) 
 
assert basic[0] is basic[1] 

所以,是的。这就是变量(以及它们指向的对象)在 Python 中的工作方式。

要获得预期的行为,您需要创建单独的列表对象:

modified = [ l.copy(), l.copy() ]