列表索引更改多个元素 [英] List index changes multiple elements
问题描述
我找不到任何与我的问题相符的内容,所以希望这在某处并没有被提及过,我发现它太愚蠢了。
I couldn't find anything matching my problem, so hopefully this wasn't already mentioned somewhere and I'm just too stupid to find it.
thelist = []
a = [0]
for i in range(5):
thelist.append(a)
print(thelist)
此时,程序返回[[0],[0],[0],[0 ],[0]]
At this point, the program returns [[0], [0], [0], [0], [0]]
thelist[0].append(1)
print(thelist)
在追加这个之后我会期望它返回相同的但是修改了第一个元素,如下所示:
After appending this I would expect it to return the same but with the first element modified, like this:
[[0, 1], [0], [0], [0], [0]]
实际发生的是,每个元素都以相同的方式被修改,我得到以下内容。
What actually happens, is that every element was modified in the same way and I get the following.
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
我发现,如果我用a的值替换第2行中的a,一切正常。但是,当我多次附加变量时,为什么这不起作用?
I have found out, that if I replace the a in line 2 with the value of a, everything works fine. But why does this not work when I append a variable multiple times??
推荐答案
创建列表时,它会保存对该列表的引用每个职位都有相同的对象(a)。当您追加到第一个元素时,它实际上附加到所有thelist插槽中。您需要做的是在构造期间对对象进行深层复制:
When creating thelist, it's saving a reference to the same object (a) in each position. When you append to the first element, it's actually appending to a in all the "thelist" slots. What you need to do is a deep copy on the object during construction:
thelist = []
a = [0]
for i in range(5):
thelist.append(list(a))
print(thelist)
然后以下附加内容将按预期工作。
Then the following append will work as desired.
这篇关于列表索引更改多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!