为什么我不能只更改Python嵌套列表中的单个元素 [英] why can't I change only a single element in a nested list in Python
问题描述
我刚刚遇到了一些Python的真正奇怪的东西:
I just met something really strange of Python:
>>> out=[[0]*3]*3
>>> out
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> out[0][1]
0
>>> out[0][1]=9
>>> out
[[0, 9, 0], [0, 9, 0], [0, 9, 0]]
好吧,很明显,我想要的是:
well, obviously, what I want is :
[[0, 9, 0], [0, 0, 0], [0, 0, 0]]
不是很奇怪吗?我对Python不太熟悉,但是Python的直观行为总是给我留下深刻的印象.但是,这是怎么回事呢?
...以及如何获得所需的东西?
isn't strange? I'm not very familiar with Python, but Python always impresses me with its intuitive behavior. But how it comes up with this?
... and how can I get what I need?
谢谢!
瓦特
推荐答案
确实是一个奇怪的行为,但这仅是因为*
运算符会生成浅表副本(在您的情况下)是[0, 0, 0]
列表的浅表副本.您可以使用id()
函数来确保这些内部列表实际上是相同的:
A strange behaviour indeed, but that's only because *
operator makes shallow copies, in your case - shallow copies of [0, 0, 0]
list. You can use the id()
function to make sure that these internal lists are actually the same:
out=[[0]*3]*3
id(out[0])
>>> 140503648365240
id(out[1])
>>> 140503648365240
id(out[2])
>>> 140503648365240
理解可以用来创建不同列表,如下所示:
Comprehensions can be used to create different lists as follows:
out = [ [0]*3 for _ in range(3) ]
这篇关于为什么我不能只更改Python嵌套列表中的单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!