基本上,我有一个嵌套的for循环在内部循环中,发生了一些事情,我可以跳过3、4、5或任何需要跳过的迭代但我不能对外环做同样的事。
希望这是有意义的。
这是我的代码:
phraseArray = []
phraseArray2 = []
counterAdd = 0
counter = 0
try:
for i in range(len(wordArray)):
for j in range(len(wordArray2)):
if wordArray[i]==wordArray2[j]:
counter = 0
counter2=3
while True:
if wordArray[i+counter]==wordArray2[j+counter]:
counter = counter+1
if counter==3:
phraseArray.append(wordArray[i+0])
phraseArray.append(wordArray[i+1])
phraseArray.append(wordArray[i+2])
elif counter>3:
phraseArray.append(wordArray[i+counter2])
counter2 = counter2+1
else:
phraseArray.append(" ")
j=j+counter
break
except IndexError:
print phraseArray2
j=j+1用于跳过某些迭代。对于外部循环,我不能这样做,因为内部循环更改了指示需要跳过多少次迭代的计数器变量有什么建议吗?
提前谢谢你们!:)
最佳答案
我会在这里使用迭代器。
import itertools
def skip(iterable, n):
next(itertools.islice(iterable, n, n), None)
outer_numbers = iter(range(...))
for i in outer_numbers:
inner_numbers = iter(range(...))
for j in inner_numbers:
if condition:
skip(outer_numbers, 3) # skip 3 items from the outer loop.
skip(inner_numbers, 2) # skip 2 items from the inner loop.
当然,您可能需要
continue
和/或break
语句。