在Python中交替使用迭代器

9 投票
6 回答
8025 浏览
提问于 2025-04-15 17:43

在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

但是有没有更高效或者更简洁的方法呢?(或者更好的是,有没有我错过的itertools函数?)

6 个回答

7

可以查看一下 roundrobin,它在 itertools 的 "Recipes" 部分有介绍,链接在这里:http://docs.python.org/3.1/library/itertools.html#recipes。这个功能是一个更通用的版本,能够实现交替的效果。

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

为了实现一个“干净”的代码,你可能需要这样写:

itertools.chain(*itertools.izip(*iters))

但也许你想要的是:

itertools.chain(*itertools.izip_longest(*iters))
8

那zip呢?你也可以试试itertools里的izip。

>>> zip(xrange(1, 7, 2),xrange(2, 8 , 2))
[(1, 2), (3, 4), (5, 6)]

如果这不是你想要的,请在你的提问中给出更多的例子。

撰写回答