【发布时间】:2021-11-19 04:38:04
【问题描述】:
我希望能够让 for 循环根据它所处的“模式”执行不同的代码,但以效率的名义不必在每次迭代时检查此模式。如果您允许这些检查,则很容易做到这一点:
for i in range(n):
if m == 0:
# execute some code, test whether to update m
continue
if m == 1:
# execute some other code, test whether to update m
但我想要的是,如果 for 循环保持其当前模式并继续运行,除非它被明确告知要更改它,以避免每次迭代时额外的“模式检查”步骤。
奇怪的是,我能想到的唯一方法是使用 goto 语句,我知道这不是答案!
i = 0
# start line for mode 1
# execute some code
i += 1
# test what mode to be in next, goto that line
# start line for mode 2
# execute some other code
i += 1
# test what mode to be in next, goto that line
# stop when you're at n
希望您能看到这两个理论程序实现了大致相同的目标,除非我以某种方式误解了。但是,第二个不必在每次 i 递增后测试其模式,因为测试接下来要处于哪种模式的动作也将它放在正确的位置以执行该模式的正确代码位。第一个运行测试并在一次迭代中更新 m,然后必须在下一次迭代中测试 m 以检查下一步要做什么。
我认为我的理论是正确的,并且 a)这些事情是不同的,b)这应该是可能的(即您不需要进行“双重测试”)。如果是这样,我需要一些帮助,请在 python 中以一种简洁的方式实现它。
【问题讨论】:
标签: python loops optimization