Creating multiple generators from one cycle

So, consider the following:

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

Since both iterators are created from the same list .. I was wondering if I could generate them together.

like

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

The above work.

But is it possible to get something like:

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

I can’t understand this.

+4
source share
2 answers
compounded_iter = ( (foo.value,bar.value(foo)) for foo in foos)
iter1,iter2 = zip(*compounded_iter)

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

+6
source
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 bar.values ​​in iter2

+1
source

Source: https://habr.com/ru/post/1568066/


All Articles