如何重复for循环

时间:2015-09-12 21:27:01

标签: python loops repeat

我遇到一个Python问题。我试图不止一次地重复一次for循环。我在循环中有一个条件,如果条件为真,循环应该重新开始。我只需要一个for循环就需要解决方案。例如:

for i in range (10):
    if i==4:
        i=0
    print(i) 

不幸的是,这不起作用。

输出应为:0 1 2 3 0 1 2 3 0 1 2 3...

3 个答案:

答案 0 :(得分:3)

在循环中写入循环变量(i)总是不是一个好主意(包括我熟悉的所有语言)。

尝试使用while循环:

i = 0
while i < 10:
    i += 1
    if i == 4:
        i = 0

可以用以下方式实现相同的逻辑:

while True:
    for i in range(4):
        print(i)

或者使用循环时常见的模运算符:

i = 0
while True:
    print(i % 4)
    i += 1

答案 1 :(得分:2)

在循环的底层将转换变量i转换为0并不意味着在下一次迭代中你的变量应为0,因为在每次迭代中,python都会自动重新赋值。

作为执行此类任务的更多pythonic方式,您可以使用itertools.cycle

>>> def range_printer(r,N): # r is the length of your range and N is the number of sequence printing 
...     a=cycle(range(r))
...     for i in range(N*r):
...         print next(a)
... 
>>> range_printer(4,3)
0
1
2
3
0
1
2
3
0
1
2
3

或者您可以使用yield返回生成器:

>>> def range_printer(r,N):
...     a=cycle(range(r))
...     for i in range(N*r):
...         yield next(a)
... 
>>> list(range_printer(4,3))
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

答案 2 :(得分:2)

使用itertools.cycle的版本:

from itertools import cycle

for i in cycle(range(4)):
    # put your logic that `break`s the cycle here
    print(i)