python-2.7 尝试修改单个值时,2D 列表有奇怪的行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2739552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:34:22  来源:igfitidea点击:

2D list has weird behavor when trying to modify a single value

pythonpython-2.7list2d

提问by Brian

Possible Duplicate:
Unexpected feature in a Python list of lists

可能的重复:
Python 列表中的意外功能

So I am relatively new to Python and I am having trouble working with 2D Lists.

所以我对 Python 比较陌生,并且在使用 2D 列表时遇到了麻烦。

Here's my code:

这是我的代码:

data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data

and here is the output (formatted for readability):

这是输出(格式化为可读性):

[['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None],
 ['Cell A1', None, None, None, None]]

Why does every row get assigned the value?

为什么每一行都被赋值?

回答by Mark Byers

This makes a list with five references to the samelist:

这将生成一个列表,其中包含对同一列表的五个引用:

data = [[None]*5]*5

Use something like this instead which creates five separate lists:

使用类似这样的东西来创建五个单独的列表:

>>> data = [[None]*5 for _ in range(5)]

Now it does what you expect:

现在它可以满足您的期望:

>>> data[0][0] = 'Cell A1'
>>> print data
[['Cell A1', None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None],
 [None, None, None, None, None]]

回答by user151019

As the python library reference for sequence types, which includes lists, says

作为序列类型python库参考,其中包括列表,说

Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

另请注意,副本很浅;不复制嵌套结构。这常常困扰着新的 Python 程序员;考虑:

>>> lists = [[]] * 3
>>> lists
  [[], [], []]
>>> lists[0].append(3)
>>> lists
  [[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list.

发生的事情是 [[]] 是一个包含空列表的单元素列表,因此 [[]] * 3 的所有三个元素都是(指向)这个单个空列表。修改列表的任何元素都会修改这个单个列表。

You can create a list of different lists this way:

您可以通过以下方式创建不同列表的列表:

>>> lists = [[] for i in range(3)]  
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
  [[3], [5], [7]]

回答by lfagundes

In python every variable is an object, and so a reference. You first created an array of 5 Nones, and then you build an array with 5 times the same object.

在python中,每个变量都是一个对象,因此是一个引用。您首先创建了一个包含 5 个 None 的数组,然后构建了一个包含 5 个相同对象的数组。