'continue' 在此 python 代码中如何工作?

how does 'continue' work in this python code?

有点疑惑,这里,"continue"执行完后,自动跳出当前迭代,并没有更新索引,对吧?

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)

关键字 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))

因此,"continue"执行后,本次迭代结束,不更新index