4

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Is there something in itertools that can even make it simpler/easier?
@Marcin oh probably :P
@JoranBeasley: citer = ((1,2) for i in range(20) ) and then iter1,iter2 = zip(*citer) But iter1.next() throws error AttributeError: 'tuple' object has no attribute 'next'??
But due to the use of * you are not creating iterators here, this is going to consume all the data.
@AshwiniChaudhary yeah I know ...I cant really come up with a good way around it .... if i dont consume it then accessing either iter returned would consume the other also ...
1
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

3 Comments

This isn't what the OP is asking—the question asked whether this can be done all at once (i.e. not in multiple lines).
I am trying to minimize the looping.. :( This has three for loops.. I am trying to get away with one.. :-/
you still have twoseparate comprehensions here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.