2010-10-04 112 views
9

前面的問題與我的has been posted具有相同的標題,(我認爲)同一個問題,但代碼中存在其他問題。我無法確定這種情況是否與我的相同。Python:替換列表中的元素(#2)

無論如何,我想替換列表中的列表中的元素。 代碼:

myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]] 
myNestedList[1][1] = 5 

我現在期待:

[[0, 0], [0, 5], [0, 0], [0, 0]] 

,但我得到:

[[0, 5], [0, 5], [0, 5], [0, 5]] 

爲什麼?

這是在命令行中複製的。 的Python 3.1.2(R312:79147,2010年4月15日,15時35分48秒) [GCC 4.4.3]上linux2上

+0

[問題在Python創建N * N * N列表(可能重複http://stackoverflow.com/questions/1889080 /問題創建-nnn-list-in-python) – SilentGhost 2010-10-04 11:48:17

回答

17

你被* 4有四個引用同一個對象,請使用替代列表理解範圍用於計數:

my_nested_list = [[0,0] for count in range(4)] 
my_nested_list[1][1] = 5 
print(my_nested_list) 

爲了解釋小更具體問題:

yourNestedList = [[0,0]]*4 
yourNestedList[1][1] = 5 
print('Original wrong: %s' % yourNestedList) 

my_nested_list = [[0,0] for count in range(4)] 
my_nested_list[1][1] = 5 
print('Corrected: %s' % my_nested_list) 

# your nested list is actually like this 
one_list = [0,0] 
your_nested_list = [ one_list for count in range(4) ] 
one_list[1] = 5 
print('Another way same: %s' % your_nested_list) 
+1

+1。起初這可能令人困惑。解釋和解決方案都很好。 – 2010-10-04 11:48:01

+0

當然,我自己也受到了這個問題的困擾;) – 2010-10-04 11:49:45

+0

啊,對初學者來說很難。非常感謝您的幫助! – reek 2010-10-04 11:56:09