如何合并两个不同的生成器,以使每次迭代中不同的生成器都能获得收益?

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


我该如何实现?我没有在itertools中找到它的功能。

最佳答案

在循环下查看itertools recipes

>>> 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

09-25 18:54