Check current index and next index equal to zero python

Asked

Viewed 206 times

3

I need to scroll through a list in Python as for example:

l = [2313, 1221, 1333, 66, 0, 0, 0, 0]

I would like it if the current element and the next on the list are zero replaces the current and next element with 1.

Or if the current and previous elements are zero: replaces the current and previous element with 1.

How could I do that?

  • 1

    Hello @Allan, I noticed your new question. But it copied wrong, beware if it is for cycle for, see below how I did

  • Wow, thank you so much Miguel! I hadn’t noticed that, I’m a beginner in Python and I need to solve an exam allocation problem, so it’s kind of tense haha I’ll pay more attention :D

  • 1

    No problem that’s what you want right?

  • Yeah yeah, great! =)

1 answer

1


You can do it like this:

l = [0, 0, 2313, 1221, 0, 1333, 66, 0, 0, 0, 0]
lCount = len(l)
next1 = False

for i in range(0, lCount-1):
    if(l[i] == 0 and l[i+1] == 0):
        l[i] = 1
        next1 = True
    elif(next1):
        l[i] = 1
        next1 = False

if(next1): # ultimo elemento caso seja 0 seguido de outro (next1 definido no ultimo loop do ciclo)
    l[-1] = 1

print(l) # [1, 1, 2313, 1221, 0, 1333, 66, 1, 1, 1, 1]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.