How to break out of multiple loops?

后端 未结 30 3327
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  执念已碎
    2020-11-21 06:09

    Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:

    def it(rows, cols, images):
        i = 0
        for r in xrange(rows):
            for c in xrange(cols):
                if i >= len(images):
                    return
                yield r, c, images[i]
                i += 1 
    
    for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
        ... do something with r, c, image ...
    

    This has the advantage of splitting up the complicated loop logic and the processing...

提交回复
热议问题