如何在python中组合来自两个生成器的元组

0 python generator

我想在一个for循环中使用两个生成器.就像是:

for a,b,c,d,e,f in f1(arg),f2(arg):
    print a,b,c,d,e,f
Run Code Online (Sandbox Code Playgroud)

其中a,b,c,d和e来自f1,f来自f2.由于空间限制,我需要使用yield运算符.

但是上面的代码不起作用.由于某种原因,它继续从f1获取值(对于所有六个变量),直到它耗尽,然后开始从f2获取值.

如果可能,请告诉我,如果没有,有任何解决方法.先感谢您.

Ble*_*der 8

您可以使用zip(itertools.izip如果您使用的是Python 2)和序列解包:

def f1(arg):
    for i in range(10):
        yield 1, 2, 3, 4, 5

def f2(arg):
    for i in range(10):
        yield 6

arg = 1

for (a, b, c, d, e), f in zip(f1(arg), f2(arg)):
    print(a, b, c, d, e, f)
Run Code Online (Sandbox Code Playgroud)