What you have is fine, but for larger loop bodies, I would use early-exit guards:
for i in list:
if not condition(i):
break
foo(i)
This has two advantages:
- One less level of indentation. Makes it easier to follow the code.
break
is now close to the condition that it belongs to. Otherwise, when reading the code, when you see break
, you'll need to go back to remember when it happens.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…