Reputation: 13
If I'm trying to move through a very small range, and want to refer to a variable created in an earlier step of the iteration, how can I reference it?
If I use a for loop with a range of say 2,6, and on the first iteration I create two variables a[i] & b[i], is it possible to reference a3 on the 4th or 5th iteration? Or something like doSomething(a[i-1],a[i])
Apologies for the terrible psuedo-code.
Upvotes: 0
Views: 1459
Reputation: 365707
You can't "manipulate the iterator". But you can do two simple things.
First, since you're apparently iterating over sequences (like range
), you can use indices. For example:
for i, value in enumerate(my_sequence):
if 3 <= i <= 4:
old_value = my_sequence[i-2]
do_something(old_value, value)
Second, you can just remember the old values:
lastlast = last = None
for value in my_sequence:
if lastlast is not None:
do_something(lastlast, value)
lastlast, last = last, value
If you want to make the second one more readable, you can pretty easily write a function that takes any iterable and iterates over overlapping groups of 3 values, so you can just do this:
for lastlast, last, value in triplets(my_sequence):
do_something(lastlast, value)
So, how do you write that triplets
function?
def triplets(iterable):
a, b, c = itertools.tee(iterable, 3)
next(b, None)
next(c, None)
next(c, None)
return itertools.izip(a, b, c)
Or, if you only care about sequences, not iterables in general, and are willing to waste some space to maybe save a little time and definitely save a bit of code:
def triplets(sequence):
return zip(sequence, sequence[1:], sequence[2:])
Upvotes: 1