我正在尝试根据事件列表中的事件列表对连续事件的索引进行分组。
但是,我的代码中附加到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)
答案 0 :(得分: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相比更清晰)。