当想要使用列表列表的索引更改值时,将列表附加到列表以生成列表列表会导致问题:python
基本上,当通过使用 list.append() 将一个列表附加到另一个列表来创建列表列表时,似乎存在问题。问题在于整个列都更改为您为给定索引设置的值。例如这里的代码
b = [1,1,1]
c = []
c.append(b)
c.append(b)
c.append(b)
c[0][0] = 4
,如果你打印 c 你会得到: [[4,1,1][4,1,1][4,1,1]] 而不是 [[4,1,1][1,1,1][1,1,1]]
所以我的问题是你如何能够最终得到右侧的列表而不是实际发生的情况。
Basically there seems to be a problem when a list of lists is made by appending a list to another list using list.append(). The problem is that the entire column is changed to the value you set it to for the index you give. for example the code here
b = [1,1,1]
c = []
c.append(b)
c.append(b)
c.append(b)
c[0][0] = 4
and if you print c you would get:
[[4,1,1][4,1,1][4,1,1]]
instead of
[[4,1,1][1,1,1][1,1,1]]
So my question is how would you be able to end up with the list to the right rather than what actually happens.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次追加列表时都创建一个新的列表副本:
您遇到问题的原因是因为列表存储为实际列表对象的引用 - 因此您的
c 版本
有 3 个相同引用的副本,全部指向同一个实际的[1,1,1]
对象。使用list()
函数创建新副本,以便引用指向单独的对象。Make a new copy of the list each time you append it:
The reason you're having problems is because lists are stored as a reference to the actual list object - and thus your version of
c
has 3 copies of the same reference, all pointing at the same actual[1,1,1]
object. Using thelist()
function makes new copies so that the references point at separate objects.您所观察到的是 Python 中的正常和预期行为,任何像样的教程都应该涵盖它。
这会向
c
附加对列表b
的三个引用。由于它是同一个列表,因此更改一个引用会更改它所引用的所有四个位置,顺便说一下,包括b
。如果您不希望出现此行为,请复制该列表。
What you've observed is normal and expected behavior in Python and any decent tutorial should cover it.
This appends to
c
three references to the listb
. Since it's the same list, changing one reference changes it in all four places it's referenced, includingb
by the way.If you don't want this behavior, copy the list.