Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the `pairwise` generator

I've got a generator similar to the itertools' pairwise recipe, which yields (s0,s1), (s1,s2), (s2, s3).... I want to create another generator from it that would yield the original sequence s0, s1, s2, s3,....

from itertools import *

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

a = [1,2,3,4]

for item in unpair(pairwise(a)):
   print item # should print 1,2,3,4

How to write unpair as a generator, without resorting to lists?

like image 396
georg Avatar asked Dec 15 '22 04:12

georg


1 Answers

Maybe:

def unpair(iterable):
    p = iter(iterable)
    return chain(next(p, []), (x[1] for x in p))
like image 161
2 revs, 2 users 92% Avatar answered Dec 28 '22 07:12

2 revs, 2 users 92%