我有:
for i in range(2,n):
if(something):
do something
else:
do something else
i = 2 **restart the loop
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.有没有办法重新启动该循环?
谢谢
基本上,我需要一种方法将控制返回到for循环的开头,并且如果满足某个条件,则在采取操作后实际重新启动整个迭代过程.
我想要做的是这样的:
for index, item in enumerate(list2):
if item == '||' and list2[index-1] == '||':
del list2[index]
*<some action that resarts the whole process>*
Run Code Online (Sandbox Code Playgroud)
这样,如果['berry','||','||','||','pancake'在列表中,我将结束:
['berry','||','pancake']相反.
谢谢!
如果我收到异常,我正在寻找重启迭代.(...它正在从服务器读取数据,偶尔会得到间歇性的错误代码,在重试时不会重复).
with open(input, 'rb') as f:
r = unicodecsv.reader(f)
for row in r:
code to request some data from server
if response_code == 200:
code to process response
else:
want to restart the iteration for the current row
Run Code Online (Sandbox Code Playgroud)
如果我正在使用while循环,这种事情显然是显而易见的(例如,不要增加数字),但鉴于我在for循环中迭代行,不能想到一种强制重新循环的方式当前迭代的内容.
虽然有很多类似的声音标题帖子(例如如何在python中重启"for"循环? ,Python - 重启for循环的方法,类似于while循环的"continue",python:重启循环 )每个我发现/读取的东西似乎得到了不同的东西(例如,当到达结束时如何重新启动,而不是在某种情况发生时重新启动迭代).
[Python 2.7]