简体   繁体   English

重新启动循环遍历列表python3

[英]restarting for cycle iterating over list python3

[python] 3.6 [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. 您好,我试图用for循环遍历列表,每当条件确定时,我都必须重新启动循环。 In CI would do: 在CI中可以做到:
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? 将for重置为列表的特定迭代的方式有哪些? Do I have to do the for in some other way? 我是否必须以其他方式进行?
Thanks for your time 谢谢你的时间

You could just use a while loop: 您可以只使用while循环:

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 使用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. while循环是最优雅的解决方案。 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)

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

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