如何在这个python代码中“继续”工作?

时间:2017-10-12 05:47:50

标签: python 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)

2 个答案:

答案 0 :(得分: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 :(得分:1)

continue moves to the next iteration of a loop.

When continue is executed, subsequent code in the loop is skipped as the loop moves to the next iteration where the iterator is updated. So for your code, once continue is executed, subsequent code (i.e., updating index and print) will be skipped as the loop will move to the next iteration:

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))

Therefore, after "continue" is executed, the current iteration ends without updating index.