2012-05-31 57 views
2

非常簡單的代碼嵌套示例:嵌套for循環python中的意外行爲

所有代碼都會創建一個初始化爲零的列表的列表。 它遍歷列表的行和列,每個位置都有一個值。 由於某些原因,打印最終矢量時,2D列表的最後一行會爲每行重複。

Number_of_channels=2 
Coefficients_per_channel=3 

coefficient_array=[[0]*Coefficients_per_channel]*Number_of_channels 
print coefficient_array 

for channel in range(Number_of_channels): 
    for coeff in range(Coefficients_per_channel): 
     coefficient_array[channel][coeff]=coeff*channel 
     print coefficient_array[channel][coeff] 

print coefficient_array 

輸出:

[[0, 0, 0], [0, 0, 0]] 
0 
0 
0 
0 
1 
2 
[[0, 1, 2], [0, 1, 2]] 

我居然想到:

[[0, 0, 0], [0, 1, 2]] 

任何人有任何想法如何走到這是怎麼回事?

回答

5

您只能複製外部的列表,但該列表的值保持不變。因此,所有(兩個)外部列表都包含對相同內部可變列表的引用。

>>> example = [[1, 2, 3]] 
>>> example *= 2 
>>> example 
[[1, 2, 3], [1, 2, 3]] 
>>> example[0][0] = 5 
[[5, 2, 3], [5, 2, 3]] 
>>> example[0] is example[1] 
True 

在一個循環中更好地創建內列表:

coefficient_array=[[0]*Coefficients_per_channel for i in xrange(Number_of_channels)] 

或,再次與Python提示符所示:

>>> example = [[i, i, i] for i in xrange(2)] 
>>> example 
[[0, 0, 0], [1, 1, 1]] 
>>> example[0][0] = 5 
>>> example 
[[5, 0, 0], [1, 1, 1]] 
>>> example[0] is example[1] 
False 
+0

感謝這個,現在我明白了。神聖的廢話,蟒蛇是強大的。 – stanri

0

嘗試此代替:

coefficient_array=[0]*Number_of_channels 
print coefficient_array 

for channel in range(Number_of_channels): 
    coefficient_array[channel] = [0] * Coefficients_per_channel 
    for coeff in range(Coefficients_per_channel): 
     coefficient_array[channel][coeff]=coeff*channel 
     print (channel, coeff) 
     print coefficient_array[channel][coeff] 

print coefficient_array 
+0

如何用'coefficient_array [channel] = range(0,Coefficients_per_channel * channel,channel)'替換內部循環? – Bittrance

1

​​

你做同樣的對象引用的重複:

coefficient_array[0] is coefficient_array[1] 

評估爲True

取而代之的是,建立你的陣列

[[coeff*channel for coeff in range(Coefficients_per_channel)] for channel in range(Number_of_channels)]