How to join/merge two generators output using python

daikini picture daikini · Dec 18, 2011 · Viewed 10.6k times · Source

I have two generators g1 and g2

for line in g1:
    print line[0]

[a, a, a]
[b, b, b]
[c, c, c]

for line1 in g2:
    print line1[0]

[1, 1, 1]
[2, 2, 2]
[3, 3, 3]

for line in itertools.chain(g1, g2):
    print line[0]

[a, a, a]
[b, b, b]
[c, c, c]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]


How

do I get the output like:

[a, a, a],[1, 1, 1]
[b, b, b],[2, 2, 2]
[c, c, c],[3, 3, 3]

or

[a, a, a, 1, 1, 1]
[b, b, b, 2, 2, 2]
[c, c, c, 3, 3, 3]


Thank You for Your help.

Answer

black panda picture black panda · Dec 18, 2011

first case: use

for x, y in zip(g1, g2):
    print(x[0], y[0])

second case: use

for x, y in zip(g1, g2):
    print(x[0] + y[0])

You can of course use itertools.izip for the generator version. You get the generator automatically if you use zip in Python 3 and greater.