2017-03-31 124 views
-1

我正在嘗試根據事件的值從事件列表中對連續事件的索引進行分組。在Python中追加到列表的列表時覆蓋

但是,我的代碼中有一個錯誤,它附加到events_list列表中,我無法發現。 當我的代碼附加它覆蓋以前附加項目的值。

最後的打印語句返回[[24],[24],[24],[24],[24]]而不是預期的[[0,1,2,3,4],[7] ,[8,9],[10,11,12],[16,17,18,19,20,21],[24]]

single_events = [1,1,1,1,1,0,0,-1,1,1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,0,0,1] 

events_list = [] 
current_event = [] 


for i, event in enumerate(single_events): 
    print('\nRecord: ', i, ',\tEvent Type: ', event) 
    if (current_event == []) and (event != 0): 
     current_event.append(i) 
     print('Current Event: ', current_event) 

    elif (current_event == []) and (acc == 0): 
     pass  

    elif (current_event != []) and (event == single_events[current_event[-1]]): 
     current_event.append(i) 
     print('Current Event: ', current_event) 

    elif (current_event != []) and (event != single_events[current_event[-1]]): 
     print('Event to be appended: ', current_event) 
     events_list.append(current_event) 
     print('\nNEW EVENT LIST!!!: ', events_list) 
     current_event[:] = [] 
     if event == 0: 
      pass 
     else: 
      current_event.append(i) 
     print('Current Event: ', current_event)   


print('\n', events_list) 

回答

1

你重複使用相同的附圖用於current_event爲每一次迭代。

即:

current_event[:] = [] 

清空列表,但保持相同的參考。您需要創建一個新的參考,以避免修改先前存儲的列表,像這樣:

current_event = [] 

只需更改,我得到:[[0, 1, 2, 3, 4], [7], [8, 9], [10, 11, 12], [16, 17, 18, 19, 20, 21]]結果

旁白:像elif (current_event == []) and (acc == 0):條件可以更好地改寫像:

elif not current_event and acc==0: 

空單被視爲「Falsy」,沒必要比較空的(同樣的事情,但acc比較0更清晰)。