在 Python 中追加到 2D 列表

发布于 2024-12-09 15:52:54 字数 455 浏览 1 评论 0原文

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

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

发布评论

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

评论(3

倥絔 2024-12-16 15:52:54

您尚未创建三个不同空列表。您创建了一个空列表,然后创建了一个新列表,其中包含对该空列表的三个引用相同。要解决此问题,请改用以下代码:

listy = [[] for i in range(3)]

现在运行示例代码会给出您可能期望的结果:

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

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]]
千纸鹤 2024-12-16 15:52:54

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

就好像您说的那样

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

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

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

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.

原谅过去的我 2024-12-16 15:52:54

来这里是为了了解如何将项目附加到二维数组,但该线程的标题有点误导,因为它正在探索附加问题。

我发现附加到二维列表的最简单方法如下:

list=[[]]

list.append((var_1,var_2))

这将产生一个包含 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=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文