简体   繁体   English

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

[英]Retrieving all iterator values from generator function

Let's say I have a generator function which yields two values: 假设我有一个生成器函数,它产生两个值:

def gen_func():
    for i in range(5):
        yield i, i**2

I want to retrieve all iterator values of my function. 我想检索我函数的所有迭代器值。 Currently I use this code snippet for that purpose: 目前,我将以下代码段用于此目的:

x1, x2 = [], []
for a, b in gen_func():
    x1.append(a)
    x2.append(b)

This works for me, but seems a little clunky. 这对我有用,但似乎有些笨拙。 Is there a more compact way for coding this? 有没有更紧凑的编码方式? I was thinking something like: 我在想类似的东西:

x1, x2 = map(list, zip(*(a, b for a, b in gen_func())))

This, however, just gives me a syntax error. 但是,这只是给我一个语法错误。

PS: I am aware that I probably shouldn't use a generator for this purpose, but I need it elsewhere. PS:我知道我可能不应该为此目的使用生成器,但是我需要在其他地方使用它。

Edit: Any type for x1 and x2 would work, however, I prefer list for my case. 编辑: x1x2任何类型都可以,但是,我更喜欢列出我的情况。

If x1 and x2 can be tuples, it's sufficient to do 如果x1x2可以是元组,则足以

>>> x1, x2 = zip(*gen_func())
>>> x1
(0, 1, 2, 3, 4)
>>> x2
(0, 1, 4, 9, 16)

Otherwise, you could use map to apply list to the iterator: 否则,您可以使用maplist应用于迭代器:

x1, x2 = map(list, zip(*gen_func()))

Just for fun, the same thing can be done using extended iterable unpacking: 只是为了好玩,使用扩展的可迭代拆包可以完成同一件事:

>>> (*x1,), (*x2,) = zip(*gen_func())
>>> x1
[0, 1, 2, 3, 4]
>>> x2
[0, 1, 4, 9, 16]

您几乎拥有它:

x1, x2 = map(list, zip(*gen_func()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM