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

时间:2016-06-07 13:42:37

标签: python list python-2.7

<table cellspacing="0" cellpadding="0" border="0" width="600"> <tr> <td width="580">Text</td> <td width="20">Image</td> </tr> </table> 循环中给出列表:a = [1, 2, 3, 4 5],假设当前项为2,下一项为3.如果某些条件为真,我怎样才能使下一项为2再次,这意味着迭代应该从2再次继续而不是3?

for

输出结果为:

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

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

1 个答案:

答案 0 :(得分:1)

小心无限循环,它不是Pythonic。

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