在Python中附加到2D列表 [英] Appending to 2D lists in Python
问题描述
我遇到了我认为在Python中很奇怪的行为,如果可能的话,我希望有人来解释它.
I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible.
我创建了一个空的2D列表
I've created an empty 2D list
listy = [[]]*3
print listy
[[], [], []]
以下功能符合我的预期:
The following works as I'd expect:
listy[1] = [1,2]
产生[[], [1,2], []]
listy[1].append(3)
产生[[], [1,2,3], []]
但是,当我追加到一个空列表之一时,python追加到所有子列表中,如下所示:
However, when I append to one of the empty lists, python appends to ALL of the sublists, as follows:
listy[2].append(1)
产生[[1], [1,2,3], [1]]
.
任何人都可以向我解释为什么会发生这种行为吗?
Can anyone explain to me why this behavior occurs?
推荐答案
您尚未创建三个不同空列表.您已经创建了一个一个空列表,然后创建了一个新列表,其中包含对该 same 空列表的三个引用.要解决此问题,请改用以下代码:
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:
listy = [[] for i in range(3)]
现在运行示例代码即可得到您可能期望的结果:
Running your example code now gives the result you probably expected:
>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]
这篇关于在Python中附加到2D列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!