在Python中的迭代器之间交替

Lea*_*orm 9 python iterator

在Python中替换从不同迭代器获取值的最有效方法是什么,例如,alternate(xrange(1, 7, 2), xrange(2, 8, 2))它将产生1,2,3,4,5,6.我知道实现它的一种方法是:

def alternate(*iters):
    while True:
        for i in iters:
            try:
                yield i.next()
            except StopIteration:
                pass
Run Code Online (Sandbox Code Playgroud)

但是有更高效或更清洁的方式吗?(或者,更好的是,itertools我错过了一个功能?)

小智 17

对于"干净"的实现,您需要

itertools.chain(*itertools.izip(*iters))
Run Code Online (Sandbox Code Playgroud)

但也许你想要

itertools.chain(*itertools.izip_longest(*iters))
Run Code Online (Sandbox Code Playgroud)

  • 在将发生器传递给izip然后链接之前,这会耗尽发电机吗? (2认同)

gho*_*g74 7

拉链怎么样?你也可以试试itertools的izip

>>> zip(xrange(1, 7, 2),xrange(2, 8 , 2))
[(1, 2), (3, 4), (5, 6)]
Run Code Online (Sandbox Code Playgroud)

如果这不是您想要的,请在您的问题帖子中提供更多示例.


Dav*_*nes 6

roundrobin 的在itertools"配方"一节.这是备用版的更通用版本.

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))
Run Code Online (Sandbox Code Playgroud)