python重构迭代,重做Python中的循环迭代

Does Python have anything in the fashion of a "redo" statement that exists in some languages?

(The "redo" statement is a statement that (just like "break" or "continue") affects looping behaviour - it jumps at the beginning of innermost loop and starts executing it again.)

解决方案

No, Python doesn't have direct support for redo. One option would something faintly terrible involving nested loops like:

for x in mylist:

while True:

...

if shouldredo:

continue # continue becomes equivalent to redo

...

if shouldcontinue:

break # break now equivalent to continue on outer "real" loop

...

break # Terminate inner loop any time we don't redo

but this mean that breaking the outer loop is impossible within the "redo-able" block without resorting to exceptions, flag variables, or packaging the whole thing up as a function.

Alternatively, you use a straight while loop that replicates what for loops do for you, explicitly creating and advancing the iterator. It has its own issues (continue is effectively redo by default, you have to explicitly advance the iterator for a "real" continue), but they're not terrible (as long as you comment uses of continue to make it clear you intend redo vs. continue, to avoid confusing maintainers). To allow redo and the other loop operations, you'd do something like:

# Create guaranteed unique sentinel (can't use None since iterator might produce None)

sentinel = object()

iterobj = iter(mylist) # Explicitly get iterator from iterable (for does this implicitly)

x = next(iterobj, sentinel) # Get next object or sentinel

while x is not sentinel: # Keep going until we exhaust iterator

...

if shouldredo:

continue

...

if shouldcontinue:

x = next(iterobj, sentinel) # Explicitly advance loop for continue case

continue

...

if shouldbreak:

break

...

# Advance loop

x = next(iterobj, sentinel)

The above could also be done with a try/except StopIteration: instead of two-arg next with a sentinel, but wrapping the whole loop with it risks other sources of StopIteration being caught, and doing it at a limited scope properly for both inner and outer next calls would be extremely ugly (much worse than the sentinel based approach).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值