Python 列表乘法:[[...]]*3 生成 3 个列表,修改后它们相互镜像
为什么会发生这种情况?我实在不明白:
>>> P = [ [()]*3 ]*3
>>> P
[[(), (), ()], [(), (), ()], [(), (), ()]]
>>> P[0][0]=1
>>> P
[[1, (), ()], [1, (), ()], [1, (), ()]]
Why this is happening? I don't really understand:
>>> P = [ [()]*3 ]*3
>>> P
[[(), (), ()], [(), (), ()], [(), (), ()]]
>>> P[0][0]=1
>>> P
[[1, (), ()], [1, (), ()], [1, (), ()]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您已 3 次引用同一个列表。
你想要这样做:
You've made 3 references to the same list.
You want to do this:
列表是可变的,将列表乘以数字不会复制其元素。您可以尝试将其更改为列表理解,因此它将计算
[()]*3
三次,创建三个不同的列表:Lists are mutable, and multiplying a list by a number doesn't copy its elements. You can try changing it to a list comprehension, so it will evaluate
[()]*3
three times, creating three different lists:它实际上是相同的内部列表(相同的引用)重复了 3 次,因此当您修改其中任何一个时,您实际上是在修改所有它们。
因此,内部列表
[()]*3
生成一个包含三个元组的列表。但是这个列表重复了三遍。然而,在Python中,它实际上是一个被相乘的引用列表,因此引用是重复的,但每个引用仍然指向相同的底层列表。It's actually the same inner list (same reference) that is duplicated 3 times, so when you modify any one of them, you are actually modifying all of them.
So, the inner list
[()]*3
produces a list of three tuples. But then this list is duplicated three times. However, in python, it's really a list of references that is being multiplied, so the reference is duplicated, but each reference still points to the same underlying list.也可以这样写,好处是可以显示结构
[[()]*3]*3
也比使用 range 稍微快一些。来自 ipython shell:
You can also write it like this, which has the advantage of showing the structure
[[()]*3]*3
It's also slightly faster than using range. From ipython shell: