0

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

➜  ~  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]]
4

1 回答 1

1

您的代码相当于这个:

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

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

board = [[None]*5 for i in range(5)]
于 2013-05-31T00:47:24.753 回答