2017-10-12 72 views
0

你能告訴我在做什麼錯誤,以及如何解決它。更新使用功能列表中的所有項目在Python

謝謝

我有一個功能。

def out(some_list): 
    test_list = [1,2,3,4] 
    result = [] 

    for i in some_list: 
     if i == 1: 
      test_list = [0,0,0,0] 
     else: 
      test_list = test_list 

     result.append(test_list) 

    return result 

,如果我們把它打印出來,則回覆:

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

我需要返回

[[0, 0, 0, 0], [1,2,3,4], [1,2,3,4], [1,2,3,4]] 
+1

是什麼'test_list = test_list'是什麼意思?你爲什麼做這個?它不會爲代碼添加任何內容。 – Antimony

+0

當我運行這個代碼時,它不返回'[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0 ,0]]'。我改用'[[1,2,3,4],[0,0,0,0],[0,0,0,0],[0,0,0,0]]'代替。請確保你的問題是正確的。 – Antimony

+1

'some_list'的價值是什麼?如果第一個元素是值「1」,那麼是的,它將是[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0, 0,0,0]]'。你不檢查你是否在第一個索引上,你正在檢查'some_list'中的值是否是'1'。 –

回答

1

這是因爲你在傳遞這個功能列表中有1作爲第一要素的價值。例如:

out([1,2,3,4]) # ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

要通過代碼一步一步:

test_list = [1,2,3,4] 
result = [] 

for i in some_list:   # The value of each element in some_list 
    if i == 1:    # If the value is "1" set test_list: [0,0,0,0] 
     test_list = [0,0,0,0] 
    else: 
     test_list = test_list # Otherwise set test_list to itself (doing nothing) 

    result.append(test_list) 

for i in some_list: 

的爲i循環值是你在some_list元素的值,它是不是索引或元素,我們在列表中的位置(因爲它出現這個問題,打算

if i == 1: 
     test_list = [0,0,0,0] 

如果該值爲1,那麼test_list將被設置爲[0,0,0,0]。一旦這個命中,只有值[0,0,0,0]將被追加到result。因此,如果第一個元素是1,那麼你只能看到結果的價值[0,0,0,0],否則你會看到[1,2,3,4],直到循環命中其中列表中some_list1

下面是一些例子:

out([0,1,2,3]) # [[1, 2, 3, 4], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
out([1,2,3,4]) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
out([2,2,5,1]) # [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [0, 0, 0, 0]] 

希望這使得它更清楚爲什麼你得到這一結果。


編輯

在更新的問題方面發生了什麼這裏要說的是,當你調用.append(fig)簡直是在內存中的參考fig的副本。基本上每當它改變你所附加的所有副本也會改變。還有,你可以處理這個問題有兩種方式,第一種是有自己的變量fig在循環的範圍界定,這樣一來它是在每個循環一個新的和不同的變量:

for i in test_list: 
    fig = [2, 1] # <== In the scope of the loop, so each fig is it's on variable 
    ... 

第二種方式是你可以追加fig[:],這意味着它將數組fig複製爲一個新的數組,並傳遞在append

for i in test_list: 

    if i == '0': 
     fig[0] = off 
     fig[1] = off 
    elif i == '1': 
     fig[0] = off 
     fig[1] = on 

    new_list.append(fig[:]) # <== Copy the array fig and append that value 
+0

嗨斯賓塞,謝謝你的解釋,但我需要根據條件重新編寫測試列表 –

+0

@Dmitriy_kzn你能澄清你的意思嗎?在問題中增加一些更多信息並加以澄清? –

+0

已編輯的問題 –

0

這是因爲你設置test_list = [0,0,0,0] 所以即使在test_list = test_list它是保持結果從它設置爲[0,0,0,0]

嘗試使用

def out(some_list): 
test_list = [1,2,3,4] 
result = [] 

for i in some_list: 
    if i == 1: 
     result.append([0,0,0,0]) 
    else: 
     result.append(test_list) 

return result 
相關問題