以循环方式耗尽一份发电机清单

2024-06-16 16:44:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个生成器函数的列表,例如:

def myGen(x):
    for i in range(x):
        yield i
g5 = myGen(5); g10 = myGen(10); g15 = myGen(15)
cycleList = [g5, g10, g15]

在这些发电机之间循环并从列表中删除耗尽的发电机的最佳方法是什么?在

输出应为:

^{pr2}$

Tags: 方法函数in列表fordefrange发电机
2条回答

循环法是一种更好的方法,但您也可以使用chainizip_longest和{a3}:

from itertools import chain, izip_longest, ifilterfalse
for x in ifilterfalse(lambda x: x is None,chain.from_iterable(izip_longest(*cycleList))):
        print x,
0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 13 14

如果没有值,请使用对象:

^{pr2}$

看起来您想要roundrobin^{} recipe

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

使用中:

^{pr2}$

相关问题 更多 >