Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join/merge two generators output using python

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.

like image 301
daikini Avatar asked Dec 18 '11 17:12

daikini


People also ask

How do you combine two Iterables in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How to use generator function in Python?

Create Generators in Python It is fairly simple to create a generator in Python. It is as easy as defining a normal function, but with a yield statement instead of a return statement. If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function.

What is a generator function in Python?

Generator functions in Python are used to create iterators and return an iterator object. In the generator function, we use a yield statement instead of a return statement. We can use multiple yield statements in the generator function.


1 Answers

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.

like image 99
black panda Avatar answered Sep 29 '22 17:09

black panda