繁体   English   中英

“继续”在此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的下一项,而不会在index添加1

举一个简单的例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM