简体   繁体   English

基于另外两个列表创建一个列表

[英]Create a list based on two other lists

What am I doing wrong?我究竟做错了什么? I am getting the error:我收到错误:

IndexError: list index out of range IndexError:列表索引超出范围

I want new_col = [0,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0]我想要 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

It's not clear to me exactly where the state machine is breaking, but it seems unnecessarily tricky.我不清楚状态机究竟在哪里中断,但这似乎不必要地棘手。 Rather than attempting to debug and fix it I'd just iterate over the ranges like this:我不会尝试调试和修复它,而是像这样迭代范围:

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

Your problem is that start_idx and end_idx are getting incremented until they're off the end of your list.您的问题是start_idxend_idx正在增加,直到它们不在您的列表末尾。

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

should be应该

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM