2017-10-12 64 views
1

我有點困惑,在這裏,執行「continue」後,它會自動跳出當前迭代,並且不會更新的索引,對吧?'繼續'如何在這個Python代碼中工作?

def method(l): 
    index = 0 
    for element in l: 

     #if element is number - skip it 
     if not element in ['(', '{', '[', ']', '}', ')']: 
      continue // THIS IS MY QUESTION 
     index = index+1 
     print("index currently is " + str(index)) 
    print("--------------------\nindex is : " + str(index)) 

t = ['4', '7', '{', '}', '('] 
method(t) 
+0

是的,你是正確的 – TerryA

+0

這絕對是一個簡單的控制檯嘗試它的例子將有助於噸:)。 – Chinny84

+0

omg,自從大學以來,我有這種知識差距....謝謝你們! – ERJAN

回答

3

關鍵字continue跳躍到在你迭代通過迭代器的下一個項目。

因此,在您的情況下,它將移動到列表l中的下一個項目,而不會將1添加到index

舉一個簡單的例子:

for i in range(10): 
    if i == 5: 
     continue 
    print(i) 

這將跳到下一個項目當它到達5,輸出:

1 
2 
3 
4 
6 
7 
8 
9 
1

continue移動到循環的下一次迭代。

當執行continue時,隨着循環移動到迭代器更新的下一個迭代,循環中的後續代碼將被跳過。因此,對於你的代碼,一旦continue執行,後續的代碼(即,更新indexprint)將被跳過的循環將移動到下一個迭代:

for element in l: 

    #if element is number - skip it 
    if not element in ['(', '{', '[', ']', '}', ')']: 
     continue # when this executes, the loop will move to the next iteration 
    # if continue executed, subsequent code in the loop won't run (i.e., next 2 lines) 
    index = index+1 
    print("index currently is " + str(index)) 
print("--------------------\nindex is : " + str(index)) 

因此,在「繼續」被執行時,當前迭代結束而不更新index

相關問題