重新启动循环迭代列表python3

2024-09-28 03:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

[python]3.6
你好,我正试图迭代一个带有for循环的列表,在这里,只要条件得到确认,就必须重新启动循环。 在C我会做:
for(i = 0; i < 10; i++){ if(list[i] == something) 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重置为列表的某个迭代?我一定要用别的方法吗?
谢谢你的时间


Tags: the方法in列表forif条件prime
3条回答

您可以使用while循环:

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

具体到您的例子:

^{pr2}$

使用itertools.takewhileutil

这里有一个人为的例子:

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")

输出:

^{pr2}$

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

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

相关问题 更多 >

    热门问题