【问题标题】:how does 'continue' work in this python code?这个 python 代码中的“继续”是如何工作的?
【发布时间】:2017-10-12 05:47:49
【问题描述】:

我有点迷茫,这里,“继续”执行后,自动跳出当前迭代,不更新索引,对吧?

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)

【问题讨论】:

  • 是的,你是对的
  • 这绝对是在一个简单的控制台中尝试它的一个例子,会帮助很多:)。
  • 天哪,我从大学开始就有这种知识差距......谢谢你们!

标签: python continue


【解决方案1】:

关键字continue 跳到您正在迭代的迭代器中的下一项。

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

举个更简单的例子:

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

当它到达5时会跳到下一个项目,输出:

1
2
3
4
6
7
8
9

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2010-12-13
      • 2013-04-23
      • 2015-04-09
      • 2013-07-24
      • 2014-03-26
      相关资源
      最近更新 更多