为什么我无法分配列表列表中的特定元素

时间:2013-05-31 00:43:52

标签: python

我不明白为什么要分配给下面每个列表中的第一个元素:

➜  ~  python
Python 2.7.3 (default, Sep 26 2012, 21:53:58) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> board = [[None]*5]*5
>>> print board
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> board[0][0] = 1
>>> print board
[[1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None]]

我希望最终输出为:

[[1, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]

1 个答案:

答案 0 :(得分:1)

您的代码与此代码相同:

x = [None]*5
board = [x for i in range(5)]

如果您想要5个不同的列表,请执行以下操作:

board = [[None]*5 for i in range(5)]