我有一些Python代码,如下所示:
for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() # HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP # SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW? # a lot more code here that scrapes the email box for interesting information正如我已经在代码中评论过的那样,如果EmailCredentialRefreshError被抛出,我希望for循环的迭代停止并移动到EmailCredentialRefreshError中的下一个项目。 我不能使用break因为这会停止整个循环,并且不会覆盖循环中的其他项目。 当然,我可以将所有代码包装在try / except中,但我想将它们紧密放在一起,以便代码保持可读性。
什么是解决这个问题的最好的Pythonic方法?
I've got some Python code as follows:
for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() # HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP # SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW? # a lot more code here that scrapes the email box for interesting informationAnd as I already commented in the code, if the EmailCredentialRefreshError is thrown I want this iteration of the for loop to stop and move to the next item in the emailCredentialsList. I can't use a break because that would stop the whole loop and it wouldn't cover the other items in the loop. I can of course wrap all the code in the try/except, but I would like to keep them close together so that the code remains readable.
What is the most Pythonic way of solving this?
最满意答案
尝试使用continue语句。 这继续到循环的下一次迭代。
for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() continue <more code>Try using the continue statement. This continues to the next iteration of the loop.
for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() continue <more code>更多推荐
发布评论