Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating multiple generators from single loop

Tags:

python

So, consider the following:

iterable1 = (foo.value for foo in foos)
iterable2 = (bar.value(foo) for foo in foos)

Since both iterables are creates from same list.. I was wondering if I can generate them together..

like

compounded_iter = ( (foo.value,bar.value(foo)) for foo in foos)

The above works..

But is it possible to get something like:

iter1, iter2 = (......)  but in one shot?

I am not able to figure that out..

like image 416
frazman Avatar asked Mar 17 '23 14:03

frazman


2 Answers

compounded_iter = ( (foo.value,bar.value(foo)) for foo in foos)
iter1,iter2 = zip(*compounded_iter)

You can, of course, combine those into one line.

like image 165
Joran Beasley Avatar answered Mar 29 '23 02:03

Joran Beasley


compounded_iter = ( (foo.value,bar.value(foo)) for foo in foos)
iter1,iter2 = [x[0] for x in compound_iter],[x[1] for x in compound_iter]

this would put all the values in iter1, and all the bar.values in iter2

like image 41
TehTris Avatar answered Mar 29 '23 03:03

TehTris