簡體   English   中英

在 Python 中使用“繼續”語句的示例?

[英]Example use of "continue" statement in Python?

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

它跳過當前迭代的其余部分(這里: print )並繼續循環的下一個迭代。

我喜歡在循環中使用 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),當沒有其他顯示停止器時。

通常 continue 是必要/有用的情況是,當您想跳過循環中的剩余代碼並繼續迭代時。

我真的不認為這是必要的,因為您始終可以使用 if 語句來提供相同的邏輯,但它可能有助於提高代碼的可讀性。

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue 是一個極其重要的控制語句。 上面的代碼是一個典型的應用,可以避免被零除的結果。 當我需要存儲程序的輸出時,我經常使用它,但如果程序崩潰了,我不想存儲輸出。 請注意,要測試上面的示例,請將最后一條語句替換為 print 1/float(x),否則只要有分數,您就會得到零,因為 randint 返回一個整數。 為了清楚起見,我省略了它。

有些人評論了可讀性,說“哦,這對可讀性沒有多大幫助,誰在乎呢?”

假設您需要在主代碼之前進行檢查:

if precondition_fails(message): continue

''' main code here '''

請注意,您可以在編寫主代碼執行此操作,而無需更改該代碼。 如果您對代碼進行比較,則只會突出顯示帶有“繼續”的添加行,因為主代碼沒有間距更改。

想象一下,如果您必須對生產代碼進行中斷修復,結果只是添加了一行繼續。 當您查看代碼時,很容易看出這是唯一的變化。 如果您開始將主代碼包裝在 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']

假設我們要打印所有不是 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

這不是絕對必要的,因為它可以使用 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語句之后沒有出現錯誤的值。

這是關於 continue 和 break 語句的非常好的可視化表示

繼續示例

資源

continue只是跳過循環中的其余代碼,直到下一次迭代

例如,如果您想根據變量的值做不同的事情:

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 語句並直接轉到循環的下一項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM