Search code examples
pythongeneratorpython-itertools

How to merge two generators in between?


How can I merge two different generators, in a way that in every iteration, a different generator will get yield?

>>> gen = merge_generators_in_between("ABCD","12")
>>> for val in gen:
...     print val
A
1
B
2
C
D

How can I achieve this? I didn't find a function for it in itertools.


Solution

  • Look in the itertools recipes under round robin:

    >>> from itertools import cycle, islice
    >>> def roundrobin(*iterables):
            "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
            # Recipe credited to George Sakkis
            pending = len(iterables)
            nexts = cycle(iter(it).next for it in iterables)
            while pending:
                try:
                    for next in nexts:
                        yield next()
                except StopIteration:
                    pending -= 1
                    nexts = cycle(islice(nexts, pending))
    
    
    >>> for x in roundrobin("ABCD", "12"):
            print x
    
    
    A
    1
    B
    2
    C
    D