我正在编写一个包含许多步骤的工作流,例如100。在每个步骤之后,我要检查条件是否为True,如果为True,则跳过所有剩余步骤并转到“下一级”。如果它一直进行到步骤100,则也转到“下一层”。
我可以想到使用for循环进行1次迭代
for i in range(1):
step1()
if condition:
break
step2()
if condition:
break
...
step100()
next level()
这似乎很好,但是有没有更好的方法而无需循环并next level
直接跳转到?如果这些步骤中再次包含这种结构,这将很有帮助,并且我不想破坏很多循环层来达到目标。next level
如果您确实有100个步骤,那将成为非常长的不可读代码。
另一种选择是将步骤/条件打包到列表中:
steps = [step1, step2, ... , step100]
conditions = [condition1, condtition2, ...]
for step, condition in zip(steps, conditions):
step()
if condition:
break
next_level()
当然,如果您的示例中只有一个全局条件,则conditions
列表不是必需的,您可以循环steps
。在这种情况下,还可以将代码进一步简化为:
steps = [step2, ... , step100]
step1()
while not condition and steps:
steps.pop(0)()
next_level()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句