use*_*864 7 python iteration for-loop
有没有办法实现这样的事情:
for row in rows:
try:
something
except:
restart iteration
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 13
您可以将try/except块放在另一个循环中,然后在成功时中断:
for row in rows:
while True:
try:
something
break
except Exception: # Try to catch something more specific
pass
Run Code Online (Sandbox Code Playgroud)
您可以使行成为迭代器,并且仅在没有错误时才前进。
it = iter(rows)
row = next(it,"")
while row:
try:
something
row = next(it,"")
except:
continue
Run Code Online (Sandbox Code Playgroud)
顺便提一句,如果您还没有,我会捕获除外中的特定错误,您并不想捕获所有内容。
如果您具有Falsey值,则可以使用object作为默认值:
it = iter(rows)
row, at_end = next(it,""), object()
while row is not at_end:
try:
something
row = next(it, at_end)
except:
continue
Run Code Online (Sandbox Code Playgroud)