重新启动循环遍历列表python3 [英] restarting for cycle iterating over list python3

查看:138
本文介绍了重新启动循环遍历列表python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[python] 3.6
您好,我试图用for循环遍历列表,每当确认条件时,我都必须重新启动循环. 在C中,我会这样做:
for(i = 0; i < 10; i++){ if(list[i] == something) i = 0; }

[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 C I would do:
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重置为列表的特定迭代的方法有哪些?我是否必须以其他方式进行?
谢谢您的时间

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

推荐答案

您可以使用while循环:

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

特定于您的示例:

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

这篇关于重新启动循环遍历列表python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆