Naming Loops in Python

前端 未结 4 2016
旧巷少年郎
旧巷少年郎 2020-12-03 17:32

I recently read this question which had a solution about labeling loops in Java.

I am wondering if such a loop-naming system exists in Python. I have been in a situa

4条回答
  •  没有蜡笔的小新
    2020-12-03 17:59

    Here's a way to break out of multiple, nested blocks using a context manager:

    import contextlib
    
    @contextlib.contextmanager
    def escapable():
        class Escape(RuntimeError): pass
        class Unblock(object):
            def escape(self):
                raise Escape()
    
        try:
            yield Unblock()
        except Escape:
            pass
    

    You can use it to break out of multiple loops:

    with escapable() as a:
        for i in xrange(30):
            for j in xrange(30):
                if i * j > 6:
                    a.escape()
    

    And you can even nest them:

    with escapable() as a:
        for i in xrange(30):
            with escapable() as b:
                for j in xrange(30):
                    if i * j == 12:
                        b.escape()  # Break partway out
                    if i * j == 40:
                        a.escape()  # Break all the way out
    

提交回复
热议问题