'继续'如何在这个Python代码中工作?

问题描述:

我有点困惑,在这里,执行“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

关键字continue跳跃到在你迭代通过迭代器的下一个项目。

因此,在您的情况下,它将移动到列表l中的下一个项目,而不会将1添加到index

举一个简单的例子:

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

这将跳到下一个项目当它到达5,输出:

1 
2 
3 
4 
6 
7 
8 
9 

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