其他语言
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
循环会上升, 但在 python 中,它不起作用
for i in range(1, 11):
if ...:
i = 4
那么我可以用'for'进入一个循环吗?
最佳答案
一种可能是您想跳过项目。与遍历索引有关的所有事情都很丑陋,但这里有一种使用 while 循环来做到这一点的方法。
i = 1
while i < 11:
if predicate(i):
i = 4
i += 1
最好直接遍历列表中你想处理的项目,跳过你不想处理的项目。
for item in some_list_of_items:
if not predicate(item):
continue
do_something_with_item(item)
或者使用生成器表达式来过滤项目
for item in (item for item in some_list_of_items if predicate(item)):
do_something_with_item(item)
关于python - 如何使用for进入python循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290399/