python - Retrieving all iterator values from generator function -
let's have generator function yields 2 values:
def gen_func(): in range(5): yield i, i**2
i want retrieve iterator values of function. use code snippet purpose:
x1, x2 = [], [] a, b in gen_func(): x1.append(a) x2.append(b)
this works me, seems little clunky. there more compact way coding this? thinking like:
x1, x2 = map(list, zip(*(a, b a, b in gen_func())))
this, however, gives me syntax error.
ps: aware shouldn't use generator purpose, need elsewhere.
edit: type x1
, x2
work, however, prefer list case.
if x1
, x2
can tuples, it's sufficient do
>>> x1, x2 = zip(*gen_func()) >>> x1 (0, 1, 2, 3, 4) >>> x2 (0, 1, 4, 9, 16)
otherwise, use map
apply list
iterator:
x1, x2 = map(list, zip(*gen_func()))
just fun, same thing can done using extended iterable unpacking:
>>> (*x1,), (*x2,) = zip(*gen_func()) >>> x1 [0, 1, 2, 3, 4] >>> x2 [0, 1, 4, 9, 16]
Comments
Post a Comment