如何正确使用嵌套循环

时间:2019-05-18 14:54:05

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

我的项目中有这个嵌套循环(当然要复杂得多,我只是简化了一下,以便您明白我的意思)。我知道python中没有标签和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()

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

1 个答案:

答案 0 :(得分: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