1

I have two functions:

def a():
    while True:
        yield stuff

def b():
    while True:
        yield otherstuff

and I want to have a loop which collects one yield from each function stored in a for a() and b for b() ; for example. If I nest the for loops which call them, it restarts the 2nd generator every-time the first loop loops. Can I have any help with this?

Thanks!

0

3 Answers 3

6

You could use itertools.izip(...) to zip the values together.

>>> def a():
        for i in xrange(10):
            yield i


>>> def b():
        for i in xrange(10, 20):
            yield i


>>> from itertools import izip
>>> for i, j in izip(a(), b()):
        print i, j


0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
Sign up to request clarification or add additional context in comments.

Comments

3
for x, y in zip(a(), b()):

It's just like simultaneously looping over any two sequences. (You may want to use itertools.izip or from future_builtins import zip to avoid gathering all the items into a big list before iterating.)

2 Comments

I don't think zip(...) would work with an infinite generator which seems to be OP's intent. Correct me if I am wrong. :)
@SukritKalra: Huh. I didn't actually read the given generators; I probably should have. They are indeed infinite, so izip or future-zip would probably be appropriate.
1

You can use izip from itertools

from itertools import izip
z = izip(a(),b())

now you have generator of tuples, first item from a() and second from b()

Comments

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.