python - 如何在for循环列表中移回迭代

问题描述:

给定列表:a = [1, 2, 3, 4 5]for循环中,假设当前项目为2,下一个项目为3.如果某些条件为真,我该如何制作下一个项目再次是2,这意味着迭代应该从2再次而不是3继续?python - 如何在for循环列表中移回迭代

a = [1, 2, 3, 4, 5] 

for item in a: 
    print item 
    if condition: 
     do something, and go back to previous iterator 

输出将是:

1 
2 
2 
3 
4 
5 
+0

重复的解决方案是不必要的通用,因为它通常处理迭代器的机制。对于一个列表,这可以很容易地用'while'循环来代替'for'来完成。 –

+1

你是什么意思?条件依赖于什么?你是否必须达到3以确定你必须再次使用2? –

+0

[也看到这里](http://stackoverflow.com/questions/2777188/making-a-python-iterator-go-backwards),如果这就是你要求的。 – ninehundred

小心无限循环的,这不是很Python的。

i = 0 
a = [1, 2, 3, 4, 5] 
hasBeenReset = False 
while i < len(a): 
    if a[i] == 3 and not hasBeenReset: 
     i = 1 
     hasBeenReset = True 
    print(a[i]) 
    i += 1 
+0

这段代码是一个无限循环。 –

+1

我更新了输出,就像原始问题中的例子一样。 – dyagmin