[英]restarting for cycle iterating over list python3
[python] 3.6
您好,我试图用for循环遍历列表,每当条件确定时,我都必须重新启动循环。 在CI中可以做到:
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重置为列表的特定迭代的方式有哪些? 我是否必须以其他方式进行?
谢谢你的时间
您可以只使用while循环:
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
您可以像使用C代码一样使用while
循环。
while i < 10: if list[i] == something: i = 0 i += 1
使用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
循环是最优雅的解决方案。 为了完整起见,您可以将列表包装到自定义生成器中,并让此新的可迭代接收信号重置循环。
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.