python中嵌套列表的意外行为

2024-04-26 05:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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。你知道吗

这种行为是故意的吗?如果是,为什么?我在文件里什么也找不到。你知道吗


Tags: 文件falsetrue列表定义basicis方式
1条回答
网友
1楼 · 发布于 2024-04-26 05:33:56

在第一个例子中:

basic = [ [0],[0] ]

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

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() ]

相关问题 更多 >