Skip to main content
 首页 » 编程设计

python之如何在两者之间合并两个生成器

2025年05月04日14bluestorm

我如何合并两个不同的生成器,在每次迭代中,不同的生成器都会获得 yield ?

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