Python列表混乱 [英] Python list confusion

查看:74
本文介绍了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天全站免登陆