简体   繁体   中英

Python: Changing the conditions of a 'for' loop

I am attempting to loop through a set of points, and if certain conditions are met, add in another point inbetween the current point and the next one. I then want to start the loop again, running over both the old and new points. For example:

  • for i in range(3)

    • If i doesn't meet a certain set of conditions, add in a new point after i .This will change the range to range(4) . End the loop, and restart with for i in range(4) .
    • If I does meet the conditions, continue in range(3) . If i reaches the end without having to add in a new point, exit the loop and continue with the rest of the code.

I have tried a variety of methods, but I can't get anything to work. My understanding would be that it is along the lines of:

b = 3
for i in range(b):
    if (i meets conditions):
        pass
    else:
        b = b+1
        "retry entire loop with new b"

I have also tried using a while loop, however I can't see how I could get this to start again at the first point, should a new point be added in.

I might be missing something simple, but I just can't see the solution to this.

Thanks for the help!

You'll need to use a recursive function for this:

def func(l):
   for i, el in enumerate(l):
       if (el match the conditions):
            l.insert(i+1, something)
            return func(l)
   return l


l = [1, 2, 3]
result = func(l)

Or use a while loop:

l = [1, 2, 3]
while True:
    i = 0
    if i >= len(l):
        break
    if (l[i] match the condition):
        l.insert(i+1, something)
        i = 0
    else:
        i += 1
b = 3
found = False
while True:
    for i in range(b):
        if (i meets conditions):
            found = True
            break # Done - breaks out
    if found:
        break
    else:
        b += 1

Using a while loop...

has_change = True
b = 3
while has_change:
    new_b = b
    for i in range(b):   
        if (i meets conditions):
            pass
        else:
            new_b = b+1
            break
    changed = new_b != b

Use a while loop to trigger new for loops

b = 3

criteria_met = False
while (criteria_met == False):
    for i in range(b):
        if (i == 1):
            b = b+1
            criteria_met = True
            break
print b

As a side note here, be careful for infinite loops when using loops like this.

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