简体   繁体   中英

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.

Edit: Any type for x1 and x2 would work, however, I prefer list for my case.

If x1 and x2 can be tuples, it's sufficient to do

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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