关于python:2D列表在尝试修改单个值时有奇怪的行为

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

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Unexpected feature in a Python list of lists

所以我对python比较陌生,在使用二维列表时遇到了困难。

以下是我的代码:

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

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

1
2
3
4
5
[['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]]

为什么每一行都被赋值?


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

1
data = [[None]*5]*5

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

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

现在它实现了您的期望:

1
2
3
4
5
6
7
>>> 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]]

作为序列类型(包括列表)的python库引用,

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

1
2
3
4
5
6
>>> 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.

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

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


在Python中,每个变量都是一个对象,因此是一个引用。首先创建一个由5个nones组成的数组,然后用同一对象的5倍构建一个数组。