【问题标题】:How to use nested loops propely如何正确使用嵌套循环
【发布时间】:2019-10-05 14:13:10
【问题描述】:

我的项目中有这个嵌套循环(当然它要复杂得多,我只是简化了它,以便您明白我的意思)。我知道python中没有label和goto,我只是想显示我想做的事情。

#goto third 行我想回到可以看到#label third 的地方。

我尝试了不同的循环设置,但它们从不做我想做的事情

import time

onoff = "on"

t=0

while onoff == "on":
    #label first
    for x in range (5):
        print("first loop")
        time.sleep(1)
        for y in range (5):
            print("second loop")
            time.sleep(1)
            p = 0    #for testing
            t=0   #for testing
            if p != 5:
                if t == 0:
                    print("third loop")
                    time.sleep(1)
                    p2 = 5    #for testing
                    t=0
                    if p2 != 5:   #label third
                        if t == 0:
                            print("go back to first loop")
                            time.sleep(1)
                            #goto first
                        else:
                            print("lock")
                            #lock.acquire()
                    else:
                        if t == 0:
                            print("go back to third loop")
                            p2 = 3
                            time.sleep(1)
                            #goto third
                        else:
                            print("lock")
                            #lock.acquire()
                else:
                    print("lock")
                    #lock.acquire()

这个嵌套循环中的每条路径似乎都可以正常工作,但我希望我的循环从#goto third 返回到#label third,然后它首先返回到#label。如何更改循环以使其成为可能?

【问题讨论】:

  • 当每个 x 完成 for y in range(5) 循环时,它最终必须从 goto third 变为 label first。如果您想要更多循环控制,那么我建议使用while 而不是for

标签: python-3.x loops nested-loops


【解决方案1】:

goto first 这样打破“for”循环的操作在很多方面都是邪恶的。 While 循环更优雅,但也许像“状态机”这样的解决方案更适合您。比如:

state = 0
while is_on:
   if state == 0:             # do outer loop things
       <do things>
       state = 1              # to do inner loop things

   elif state == 1:
       n = 0
          # do inner loop things 
       n += 1
       if n == 5:
           state = 0

   elif state == 2:            # do even more nested things
       p = 0
       if <some condition>:
           state = 0
       p += 1
       if p == 5:
          state = <whatever>

状态机允许更大的灵活性。此外,它不会像嵌套循环那样导致缩进。如果复杂性变大,有一些库可以帮助您。有限状态机上的有趣链接 (FSM):

https://python-3-patterns-idioms-test.readthedocs.io/en/latest/StateMachine.html

https://www.python-course.eu/finite_state_machine.php

【讨论】:

  • 是的,我想我可以使用这种方法。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2013-10-22
  • 2021-10-09
  • 2017-11-01
  • 2017-06-04
  • 1970-01-01
相关资源
最近更新 更多