从生成器函数中检索所有迭代器值

Nyp*_*yps 1 python iterator generator

假设我有一个生成函数,它产生两个值:

def gen_func():
    for i in range(5):
        yield i, i**2
Run Code Online (Sandbox Code Playgroud)

我想检索我的函数的所有迭代器值.目前我为此目的使用此代码段:

x1, x2 = [], []
for a, b in gen_func():
    x1.append(a)
    x2.append(b)
Run Code Online (Sandbox Code Playgroud)

这对我有用,但看起来有点笨重.是否有更紧凑的编码方式?我想的是:

x1, x2 = map(list, zip(*(a, b for a, b in gen_func())))
Run Code Online (Sandbox Code Playgroud)

但是,这只会给我一个语法错误.

PS:我知道我可能不应该为此目的使用发电机,但我需要其他地方.

编辑:任何类型的x1x2将工作,但是,我更喜欢列表我的情况.

vau*_*tah 5

如果x1并且x2可以是元组,那就足够了

>>> x1, x2 = zip(*gen_func())
>>> x1
(0, 1, 2, 3, 4)
>>> x2
(0, 1, 4, 9, 16)
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用map以应用于list迭代器:

x1, x2 = map(list, zip(*gen_func()))
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,使用扩展的可迭代解包可以完成同样的事情:

>>> (*x1,), (*x2,) = zip(*gen_func())
>>> x1
[0, 1, 2, 3, 4]
>>> x2
[0, 1, 4, 9, 16]
Run Code Online (Sandbox Code Playgroud)