2015-10-23 59 views
0

我想準備包含將在蠻力搜索中使用的所有可能參數組合的列表列表。所述參數的組合應該是這樣的:附加覆蓋每個帶有最後附加值的元素(Python)

[0,0,1]
[0,0.2,0.8]
[0.2,0,0.8]
...
[0.4,0.4,0.2 ]
...
[1,0,0]

代碼生成這些名單只是罰款 - 打印weights_temp在每次迭代返回正確的結果。但是,追加有一些問題。當我打印,我得到的是這樣的(最後weights_temp值,而不是其他因素):

[1.0,0.0,0.0]
[1.0,0.0,0.0]
...
[1.0,0.0,0.0]
...
[1.0,0.0,0.0]

這是我的代碼:

step = 0.2 

weights_temp = [0, 0, 1] 
weights = [weights_temp] 

i = 1 

while weights_temp != [1, 0, 0]: 
    # decrease gamma 
    weights_temp[2] = 1 - i * step 

    for j in xrange(0, i + 1): 
     # increase alpha, decrease beta 
     weights_temp[0] = j * step 
     weights_temp[1] = abs(1 - weights_temp[2]) - j * step 

     weights.append(weights_temp) 

     print weights_temp 

    i += 1 

有誰知道如何解決這個問題?

預先感謝您

+0

'weights.append(weights_temp)'是每次追加同樣的事情,因爲weights_temp,據我所知,是參考/指向數據的指針。即,而不是附加一個新列表並更改該列表,您將追加相同的引用並每次更改該引用的數據。如果每次追加時都打印「權重」,則可能會看到每個列表都會每次更新 –

回答

0

與我的評論繼續,而不是添加引用,每次你用列表解析添加時間做出一個新的列表。

weights.append([item for item in weights_temp]) 

實施例:

>>> temp = [1,2,3] 
>>> holder = [temp] 
>>> holder 
[[1, 2, 3]] 
>>> temp[0] += 1 
>>> holder 
[[2, 2, 3]] 
>>> holder.append([item for item in temp]) 
>>> holder 
[[2, 2, 3], [2, 2, 3]] 
>>> temp[0] +=1 
>>> holder 
[[3, 2, 3], [2, 2, 3]]