附加到Python中的2D列表

时间:2022-10-29 18:10:34

I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible.

我在Python中遇到了我认为是奇怪的行为,如果可能的话,我希望有人解释一下。

I've created an empty 2D list

我创建了一个空的2D列表

listy = [[]]*3

print listy

[[], [], []]

The following works as I'd expect:

以下工作正如我所料:

listy[1] = [1,2] yields [[], [1,2], []]

listy [1] = [1,2]得[[],[1,2],[]]

listy[1].append(3) yields [[], [1,2,3], []]

listy [1] .append(3)产生[[],[1,2,3],[]]

However, when I append to one of the empty lists, python appends to ALL of the sublists, as follows:

但是,当我附加到其中一个空列表时,python会附加到所有子列表,如下所示:

listy[2].append(1) yields [[1], [1,2,3], [1]].

listy [2] .append(1)得[[1],[1,2,3],[1]]。

Can anyone explain to me why this behavior occurs?

谁能向我解释为什么会出现这种情况?

2 个解决方案

#1


45  

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]]

#2


12  

[[]]*3 is not the same as [[], [], []].

[[]] * 3与[[],[],[]]不同。

It's as if you'd said

就像你说的那样

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

换句话说,所有三个列表引用都引用相同的列表实例。

#1


45  

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]]

#2


12  

[[]]*3 is not the same as [[], [], []].

[[]] * 3与[[],[],[]]不同。

It's as if you'd said

就像你说的那样

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

换句话说,所有三个列表引用都引用相同的列表实例。