I would like an enumerate
-like functional on iterators which yields the pair (previous_element, current_element)
. That is, given that iter
What about the simple (obvious) solution?
def offset(iterable):
prev = None
for elem in iterable:
yield prev, elem
prev = elem
The best answer I have (and this requires itertools
) is
def offset(iter, n=1):
# returns tuples (None, iter0), (iter0, iter1), (iter1, iter2) ...
previous = chain([None] * n, iter)
return izip(previous, iter)
but I would be interested in seeing if someone has a one-liner (or a better name than offset for this function)!
def pairwise(iterable):
"""s -> (s0,s1), (s1,s2), (s2, s3), ...
see http://docs.python.org/library/itertools.html
"""
a, b = itertools.tee(iterable)
b.next()
return itertools.izip(a, b)
EDIT moved doc string into the function
def offset(iter, n=1, pad=None):
i1, i2 = itertools.tee(iter)
i1_padded = itertools.chain(itertools.repeat(pad, n), i1)
return itertools.izip(i1_padded, i2)
@bpgergo + @user792036 = this. Best of two worlds :).
To put more itertools on the table:
from itertools import tee, izip, chain
def tee_zip(iterable):
a, b = tee(iterable)
return izip(chain([None], a), b)