frazman
frazman

Reputation: 33243

creating multiple generators from single loop

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

Upvotes: 4

Views: 74

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113978

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.

Upvotes: 6

TehTris
TehTris

Reputation: 3217

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

Upvotes: 1

Related Questions