简体   繁体   中英

restarting for cycle iterating over list python3

[python] 3.6
Hello, I was trying to iterate over a list with a for cycle, where I had to restart the cycle whenever a condition was confirmed. In CI would do:
for(i = 0; i < 10; i++){ if(list[i] == something) i = 0; }

Here I was trying to do this:

for x in listPrimes:
    if((num % x) == 0):
        num /= x # divide by the prime
        factorials.append(x)
        x = 2 # reset to the first prime in the list?

which doesn't work correctly. What are the ways to reset the for to a certain iteration of the list? Do I have to do the for in some other way?
Thanks for your time

You could just use a while loop:

i = 0
while i < 10:
    print("do something", i)
    if random.random() < 0.2:
        print("reset")
        i = -1
    i += 1

Specific to your example:

i = 0
while i < len(listPrimes):
    x = listPrimes[i]
    if num % x == 0:
        num /= x
        factorials.append(x)
        i = -1
    i += 1

您可以像使用C代码一样使用while循环。

while i < 10: if list[i] == something: i = 0 i += 1

Use itertools.takewhile util

Here is a contrived example:

import itertools

li = [1,2,3,4,5]
for i in range(1, 6):
        print(list(itertools.takewhile(lambda x: x!=i, li)))
        print("new cycle")

Output:

[]
new cycle
[1]
new cycle
[1, 2]
new cycle
[1, 2, 3]
new cycle
[1, 2, 3, 4]
new cycle

The while loop is the most elegant solution. Just for completeness you could wrap your list into custom generator and let this new iterable receive signal to reset the loop.

import time

def resetable_generator(li):
    while True:
        for item in li:
            reset = yield item
            if reset:
                break
        else:
            raise StopIteration


x = range(10)
sum = 0
r = resetable_generator(x)
for item in r:
    time.sleep(1)
    sum += item
    if item == 6:
        sum += r.send(True)
    print(sum)

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