Python 列表乘法:[[...]]*3 生成 3 个列表,修改后它们相互镜像

发布于 2024-11-23 18:44:45 字数 217 浏览 0 评论 0原文

为什么会发生这种情况?我实在不明白:

>>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你是我的挚爱i 2024-11-30 18:44:45

您已 3 次引用同一个列表。

>>> a = b = []
>>> a.append(42)
>>> b
[42]

你想要这样做:

P = [[()] * 3 for x in range(3)]

You've made 3 references to the same list.

>>> a = b = []
>>> a.append(42)
>>> b
[42]

You want to do this:

P = [[()] * 3 for x in range(3)]
追我者格杀勿论 2024-11-30 18:44:45

列表是可变的,将列表乘以数字不会复制其元素。您可以尝试将其更改为列表理解,因此它将计算 [()]*3 三次,创建三个不同的列表:

P = [ [()]*3 for i in range(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:

P = [ [()]*3 for i in range(3) ]
酒儿 2024-11-30 18:44:45

它实际上是相同的内部列表(相同的引用)重复了 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.

攒一口袋星星 2024-11-30 18:44:45

也可以这样写,好处是可以显示结构 [[()]*3]*3

>>> P=[i[:] for i in [[()]*3]*3]
>>> P[0][0]=1
>>> P
[[1, (), ()], [(), (), ()], [(), (), ()]

也比使用 range 稍微快一些。来自 ipython shell:

In [1]: timeit P = [ [()]*3 for i in range(3) ]
1000000 loops, best of 3: 1.41 us per loop

In [2]: timeit P=[i[:] for i in [[()]*3]*3]
1000000 loops, best of 3: 1.27 us per loop

You can also write it like this, which has the advantage of showing the structure [[()]*3]*3

>>> P=[i[:] for i in [[()]*3]*3]
>>> P[0][0]=1
>>> P
[[1, (), ()], [(), (), ()], [(), (), ()]

It's also slightly faster than using range. From ipython shell:

In [1]: timeit P = [ [()]*3 for i in range(3) ]
1000000 loops, best of 3: 1.41 us per loop

In [2]: timeit P=[i[:] for i in [[()]*3]*3]
1000000 loops, best of 3: 1.27 us per loop
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文