ステートメントの定義は次のとおりです。continue
ステートメントは、ループの
continue
次の繰り返しで続行されます。
コードの良い例が見つかりません。
誰かcontinue
が必要ないくつかの簡単なケースを提案できますか?
簡単な例を次に示します。
for letter in 'Django':
if letter == 'D':
continue
print("Current Letter: " + letter)
出力は次のようになります。
Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o
ループの次の繰り返しに進みます。
私は、「本題に入る」前に満たさなければならない多くの条件があるループで continue を使用するのが好きです。したがって、次のようなコードの代わりに:
for x, y in zip(a, b):
if x > y:
z = calculate_z(x, y)
if y - z < x:
y = min(y, z)
if x ** 2 - y ** 2 > 0:
lots()
of()
code()
here()
次のようなコードを取得します。
for x, y in zip(a, b):
if x <= y:
continue
z = calculate_z(x, y)
if y - z >= x:
continue
y = min(y, z)
if x ** 2 - y ** 2 <= 0:
continue
lots()
of()
code()
here()
このようにすることで、非常に深くネストされたコードを回避できます。また、最も頻繁に発生するケースを最初に除外することでループを最適化するのは簡単です。そのため、他にショーストッパーがない場合は、まれではあるが重要なケース (除数が 0 など) のみを処理する必要があります。
通常、続行が必要/有用な状況は、ループ内の残りのコードをスキップして反復を続行する場合です。
いつでも if ステートメントを使用して同じロジックを提供できるため、必ずしも必要だとは思いませんが、コードの可読性を高めるのに役立つ場合があります。
一部の人々は読みやすさについてコメントしており、「ああ、読みやすさにはあまり役立たない。誰が気にする?」と言っています。
メインコードの前にチェックが必要だとします:
if precondition_fails(message): continue
''' main code here '''
とにかくそのコードを変更せずに、メインコードが書かれた後にこれを行うことができることに注意してください。コードを比較すると、メイン コードに間隔の変更がないため、"continue" で追加された行のみが強調表示されます。
生産コードのブレークフィックスを実行する必要がある場合を想像してみてください。これは、continue を含む行を追加するだけであることが判明しました。コードを確認すると、これが唯一の変更点であることが簡単にわかります。if/else でメイン コードをラップし始めると、間隔の変更を無視しない限り、diff は新しくインデントされたコードを強調表示します。これは特に Python では危険です。コードをすぐに展開しなければならないような状況にない限り、これを十分に理解できないかもしれません。
def filter_out_colors(elements):
colors = ['red', 'green']
result = []
for element in elements:
if element in colors:
continue # skip the element
# You can do whatever here
result.append(element)
return result
>>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
['lemon', 'orange', 'pear']
IF を使用して実行できるため、絶対に必要というわけではありませんが、読みやすく、実行時のコストも低くなります。
データがいくつかの要件を満たさない場合、ループ内の反復をスキップするために使用します。
# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]
for time in commit_times:
hour = time[0]
minutes = time[1]
# If the hour is not between 0 and 24
# and the minutes not between 0 and 59 then we know something is wrong.
# Then we don't want to use this value,
# we skip directly to the next iteration in the loop.
if not (0 <= hour <= 24 and 0 <= minutes <= 59):
continue
# From here you know the time format in the tuples is reliable.
# Apply some logic based on time.
print("Someone commited at {h}:{m}".format(h=hour, m=minutes))
出力:
Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45
ご覧のとおり、間違った値はcontinue
ステートメントの後にはなりませんでした。
3 と 5 の倍数ではないすべての数値を出力したいとしましょう
for x in range(0, 101):
if x % 3 ==0 or x % 5 == 0:
continue
#no more code is executed, we go to the next number
print x
たとえば、変数の値に応じて異なることをしたい場合:
my_var = 1
for items in range(0,100):
if my_var < 10:
continue
elif my_var == 10:
print("hit")
elif my_var > 10:
print("passed")
my_var = my_var + 1
上記の例ではbreak
、インタープリターを使用するとループがスキップされます。ただしcontinue
、if-elif ステートメントをスキップするだけで、ループの次の項目に直接進みます。