基于其他两个列表创建一个列表

Create a list based on two other lists

我做错了什么?我收到错误:

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

我不清楚状态机到底在哪里坏了,但这似乎是不必要的棘手。我没有尝试调试和修复它,而是像这样遍历范围:

>>> 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]

您的问题是 start_idxend_idx 会递增,直到它们超出列表的末尾。

starts = [1,5,9,13]
ends = [3,7,10,16]

应该是

starts = [1,5,9,13,21]
ends = [3,7,10,16,21]