在 Python 中追加到 2D 列表
我在 Python 中遇到了我认为奇怪的行为,如果可能的话,我希望有人能解释一下。
我创建了一个空的 2D 列表
listy = [[]]*3
print listy
[[], [], []]
以下内容按我的预期工作:
listy[1] = [1,2]
产生 [[], [1,2], [] ]
listy[1].append(3)
产生 [[], [1,2,3], []]
但是,当我附加到空列表之一,python 附加到所有子列表,如下所示:
listy[2].append(1)
产生 [[1], [1,2,3], [1]]
。
谁能向我解释为什么会出现这种行为?
I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible.
I've created an empty 2D list
listy = [[]]*3
print listy
[[], [], []]
The following works as I'd expect:
listy[1] = [1,2]
yields [[], [1,2], []]
listy[1].append(3)
yields [[], [1,2,3], []]
However, when I append to one of the empty lists, python appends to ALL of the sublists, as follows:
listy[2].append(1)
yields [[1], [1,2,3], [1]]
.
Can anyone explain to me why this behavior occurs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尚未创建三个不同空列表。您创建了一个空列表,然后创建了一个新列表,其中包含对该空列表的三个引用相同。要解决此问题,请改用以下代码:
现在运行示例代码会给出您可能期望的结果:
You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:
Running your example code now gives the result you probably expected:
[[]]*3
与[[], [], []]
不同。就好像您说的那样
,换句话说,所有三个列表引用都引用同一个列表实例。
[[]]*3
is not the same as[[], [], []]
.It's as if you'd said
In other words, all three list references refer to the same list instance.
来这里是为了了解如何将项目附加到二维数组,但该线程的标题有点误导,因为它正在探索附加问题。
我发现附加到二维列表的最简单方法如下:
list=[[]]
这将产生一个包含 2 个变量 var_1、var_2 的条目。希望这有帮助!
Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.
The easiest way I found to append to a 2D list is like this:
list=[[]]
This will result in an entry with the 2 variables var_1, var_2. Hope this helps!