Help us understand the problem. What is going on with this article?

多重ループを一気に抜ける

More than 5 years have passed since last update.

pythonには多重ループを抜ける簡単な方法が用意されてない。
フラグを用意すればいいけどあんまりきれいじゃない

flag = False
for i in range(100):
    for j in range(100):
        if i > j > 70:
            flag = True
            break
        print i, j
    if flag:
        break

そんなforループは構造から見直せってことなのだと思うけど。どうしてもbreakで多重ループを抜けてほしいときがある。
そんな時は

  • for-else句を使う
  • try-except構文を使う
  • gotoモジュールを使う とかがあるっぽい。

for-else句を使う

for i in range(100):
    for j in range(100):
        if i > j > 70:
            break
        print i, j
    else:
        continue
    break

あんまきれいじゃない

try-except構文を使う

try:
    for i in range(100):
        for j in range(100):
            if i > j > 70:
                raise Exception
            print i, j
except Exception:
    pass

本来の使い方と違うしあんま好きになれないな~

gotoをつかう

goto for Python

from goto import goto, label

for i in range(100):
    for j in range(100):
        if i > j > 70:
            goto .END
        print i, j
label .END

わかりやすいけど外部モジュールのインストールが必要

どれもいまいちだしやっぱ関数化しろってことですね。
はい。

airtoxin
いい感じにやってます
https://airtoxin.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした