2013-05-31 137 views
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]] 
+0

這是因爲所有列表'[None,None,None,None,None]'是同一對象的副本,修改所有列表。 –

回答

1

你的代碼是等效於此:

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

如果你想5個不同的列表,這樣做:

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

啊,我明白了。謝謝。 – xbonez

相關問題