Reputation: 6418
Is there some way to move the index forward in a for loop in python? For example, if I'm iterating through a string and find some char that I'm looking for, can I begin reading from that position on the next iteration of the for loop?
Like, after reading an x, read until a y and start from the position following the y on the next iteration:
for i in range(len(myString)):
if myString[i] == 'x':
j = i + 1
while( myString[j] != '\n' ):
if( myString[j] == 'y' ):
i = j + 1 # start at position following y in string on the next iteration
j = j + 1
Or do I have to use a while loop to achieve this?
Upvotes: 0
Views: 511
Reputation: 34166
You could try using an infinite loop:
while true:
if i >= len(myString): # Exit condition
break
# do something with myString[i]
# set i as you want
Upvotes: 1
Reputation: 51847
Now, effectively you're still using a while
loop here - but I think this comes closer in spirit to what you were thinking about:
def myrange(limit=0):
counter = 0
while counter < limit:
next = yield counter
try:
counter = int(next) - 1
except TypeError:
counter += 1
mylist = ['zero', 'one', 'two', 'five', 'four']
my_iter = myrange(len(mylist))
for i in my_iter:
print(mylist[i])
if mylist[i] == 'five':
print('-- three, sir! --')
mylist[i] = 'three!'
my_iter.send(i)
elif mylist[i] == 'four':
print("Don't count that number!")
This works because of the send
function that generators have. They allow you to send a value to the generator that the generator can then use how it wishes. Note that when you call .send()
on a generator that it will yield the next value (so when we call my_iter.send(i)
, it's actually yield
ing the next value. That's why we call counter = int(next) - 1
. The alternative would be to put the -1
in your for
loop.
Upvotes: 1
Reputation: 1635
You can use an string instead of list in this sample code. It finds the first x in the remaining part of the list, then finds the first y after that 'x' and so on
#mylist = [list to search]
i = 0
while true:
list_to_search = mylist[i:]
if 'x' not in list_to_search:
break
j = list_to_search.index('x')
if 'y' not in list_to_search[j+1:]:
break
i = list_to_search.index('y')
(x_pos,y_pos) = (j,i)
#your code
Upvotes: 2