Python 列表混淆 [英] Python list confusion

查看:18
本文介绍了Python 列表混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

a_list = [[0]*10]*10

这会生成以下列表:

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

然后我想修改第一个列表中的第一个元素:

Then I want to modify the first element in the first list:

a_list[0][0] = 23

我希望只修改列表的第一个元素,但实际上每个列表的第一个元素都被更改了:

I expected only the first element of the list to be modified, but actually the first element of each list was changed:

[[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [23, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

我设法找到了另一种表示我的数据的方法来避免这种情况,但为什么会发生这种情况?为什么不只是第一个列表改变?当我执行第二个 *10 时,Python 是否真的复制了第一个列表的地址而不是分配新的内存块?

I managed to find another way to represent my data to avoid this but why is this happening? Why isn't just the first list changed? When I do the second *10, does Python actually copy the first list's address instead of allocating a new memory block?

推荐答案

您对复制地址的预感是正确的.可以这样想:

Your hunch about copying addresses is correct. Think about it like this:

sub_list = [0] * 10
a_list = [sub_list] * 10

这段代码实际上等同于您在上面发布的代码.这意味着每当您更改 a_list 的任何元素时,您实际上都在更改相同的列表 sub_list.您甚至可以通过键入以下内容来确保它:

This code is actually equivalent to the code you have posted above. What this means is that you are actually changing the same list sub_list whenever you change any element of a_list. You can even make sure of it by typing:

a_list = [[0] * 10] * 10
for n in a_list:
    print id(n)

它会为每个元素显示相同的内容.要解决此问题,您应该使用:

And it will show up the same for every element. To remedy this, you should use:

a_list = [[0] * 10 for _ in range(10)]

为了为a_list的每个元素创建一个新的子列表.

In order to create a new sublist for every element of a_list.

这篇关于Python 列表混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆