简体   繁体   中英

Create a list based on two other lists

What am I doing wrong? I am getting the error:

IndexError: list index out of range

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]

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.

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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