我做错了什么?我收到错误:
IndexError: 列表索引超出范围
我想要 new_col = [0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0]
starts = [1,5,9,13]
ends = [3,7,10,16]
new_col = []
check = 0
start_idx = 0
end_idx = 0
for i in range(20):
if i == starts[start_idx]:
check += 1
new_col.append(check)
start_idx += 1
continue
elif i == ends[end_idx]:
check -= 1
new_col.append(check)
end_idx += 1
continue
else:
new_col.append(check)
continue
答案 0 :(得分:3)
我不清楚状态机究竟在哪里中断,但这似乎不必要地棘手。我不会尝试调试和修复它,而是像这样迭代范围:
>>> starts = [1,5,9,13]
>>> ends = [3,7,10,16]
>>> new_col = [0] * 20
>>> for start, end in zip(starts, ends):
... for i in range(start, end):
... new_col[i] = 1
...
>>> new_col
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
答案 1 :(得分:0)
您的问题是 start_idx
和 end_idx
一直在递增,直到它们不在列表的末尾。
starts = [1,5,9,13]
ends = [3,7,10,16]
应该
starts = [1,5,9,13,21]
ends = [3,7,10,16,21]