gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:54 26 4
gpt4 key购买 nike

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

关于python - 'continue' 在此 python 代码中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com