Reputation: 41
Basically, I have a nested for loop. In the inner loop, something happens, and I can skip 3,4,5 or however many iterations i need skipped. But I can't do the same for the outer loop. Hope that made sense. Here is my code:
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
The j = j+1 is used to skip certain iterations. I cant do the same for the outer loop because the inner loop changes the counter variable which dictates how many iterations need to skipped. Any suggestions?
Thanks in advance guys! :)
Upvotes: 3
Views: 1485
Reputation: 309821
I'd work with iterators here.
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.
Of course, you may want/need continue
and/or break
statements.
Upvotes: 3
Reputation: 128
You can't use "break" in the outer loop because this will finish the loop and not skip it, what you can do is use some IF statements to control the cases you want. something like
if(condition=skip):
#do nothing
else:
# do
Upvotes: 2
Reputation: 86064
A general form for skipping multiple iterations of a loop could work like this.
skips = 0
for x in y:
if skips:
skips -= 1
continue
#do your stuff
#maybe set skips = something
Upvotes: 3