在Python中,如何继续
父循环,假设有两个嵌套的循环?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
我知道在大多数情况下你可以避免这种情况,但是在Python中能做到吗?
在Python中,如何继续
父循环,假设有两个嵌套的循环?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
我知道在大多数情况下你可以避免这种情况,但是在Python中能做到吗?
每次我都会选择5。
break
和 continue
有级别选项 :) - jave.web创建一个本地函数
for a in b:
def doWork():
for c in d:
for e in f:
if somecondition:
return # <continue the for a in b loop?>
doWork()
更好的选择是将doWork移动到其他地方,并将其状态作为参数传递。class StopLookingForThings(Exception): pass
for a in b:
try:
for c in d:
for e in f:
if somecondition:
raise StopLookingForThings()
except StopLookingForThings:
pass
break
来跳出内部循环,并继续执行外部循环的代码。for a in b:
for c in d:
if somecondition:
break # go back to parent loop
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break
使用布尔标志
problem = False
for a in b:
for c in d:
if problem:
continue
for e in f:
if somecondition:
problem = True
看到这里所有的答案都与我做法不同\n任务: 如果嵌套循环中的if条件为真,则继续while循环
chars = 'loop|ing'
x,i=10,0
while x>i:
jump = False
for a in chars:
if(a = '|'): jump = True
if(jump==True): continue
#infinite wait till all items obtained
while True:
time.sleep(0.5)
for item in entries:
if self.results.get(item,None) is None:
print(f"waiting for {item} to be obtained")
break #continue outer loop
else:
break
#continue
我希望能有一个带标签的循环...
lista = ["hello1", "hello2" , "world"]
for index,word in enumerate(lista):
found = False
for i in range(1,3):
if word == "hello"+str(i):
found = True
break
print(index)
if found == True:
continue
if word == "world":
continue
print(index)
现在打印的是:
>> 1
>> 2
>> 2
这意味着第一个单词(索引=0)首先出现(在 continue 语句之前没有任何东西可以被打印)。第二个单词(索引=1)出现在第二个位置(单词“hello1”得以打印,但其余的未能打印),第三个单词出现在第三个位置,这意味着在 for 循环到达第三个单词之前,“hello1”和“hello2”这两个单词已经被打印。
总之,这只是使用 found = False / True 布尔值和 break 语句。
希望对你有所帮助!
break
? - Jon Clementsbreak
来退出内部循环 - 这将立即继续执行外部循环。 - TyrantWave