Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在列表python3上重新启动循环迭代_Python_Python 3.x_List_For Loop - Fatal编程技术网

在列表python3上重新启动循环迭代

在列表python3上重新启动循环迭代,python,python-3.x,list,for-loop,Python,Python 3.x,List,For Loop,[python]3.6 您好,我正试图用for循环遍历一个列表,在这个列表中,只要一个条件得到确认,我就必须重新启动循环。 在C语言中,我会这样做: (i=0;i

[python]3.6
您好,我正试图用for循环遍历一个列表,在这个列表中,只要一个条件得到确认,我就必须重新启动循环。 在C语言中,我会这样做:
(i=0;i<10;i++)的
{
如果(列出[i]==某物)
i=0;
}

在这里,我试图做到这一点:

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?
它不能正常工作。有哪些方法可以将for重置为列表的某个迭代?我是否必须以其他方式为您服务?

感谢您的时间

您可以使用与C代码类似的
while
循环

当i<10时:
如果列表[i]==某物:
i=0

i+=1

您可以使用while循环:

i = 0
while i < 10:
    print("do something", i)
    if random.random() < 0.2:
        print("reset")
        i = -1
    i += 1
i=0
当我<10时:
打印(“做点什么”,i)
如果random.random()<0.2:
打印(“重置”)
i=-1
i+=1
具体到您的示例:

i = 0
while i < len(listPrimes):
    x = listPrimes[i]
    if num % x == 0:
        num /= x
        factorials.append(x)
        i = -1
    i += 1
i=0
而i
使用
itertools.takewhile
util

下面是一个人为的例子:

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")
输出:

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

while
循环是最优雅的解决方案。为了完整起见,您可以将列表包装到自定义生成器中,让这个新的iterable接收信号来重置循环

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)

答案很好,只需将if中的i=0更改为i=-1,或者继续,因为之后i将递增。感谢可能的副本