Jack Arnestad
Jack Arnestad

Reputation: 1865

Element wise merging of lists python

To merge the elements of two lists like the following, it is very easy:

one = [['hi', 'hello'], ['namaste']]
two = [['hi', 'bye'], ['namaste']]

[m+n for m,n in zip(one,two)]

However, if I had a list greater than length 2, how can this be done? For example, concatenating each element in the list of list of lists that follows:

three = [['hi', 'why'], ['bye']]
list_ = [one, two, three]

I want an output like: [['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']]

How can this be done in a scalable way, which works with even a list_ of length 10?

Upvotes: 2

Views: 99

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

You could use extended iterable unpacking operator in combination with zip method.

from itertools import chain
one = [['hi', 'hello'], ['namaste']]
two = [['hi', 'bye'], ['namaste']]
three = [['hi', 'why'], ['bye']]
list_ = [one, two, three]
result = [list(chain.from_iterable(elem)) for elem in zip(*list_)]

Output

[['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']]

Upvotes: 1

Harshita
Harshita

Reputation: 488

Assuming that they're all the same size:

a = []

for i in len(one):
    a.append([])
    for list in list_:
        a[-1] += list[1]

even better, in a list comprehension:

import itertools    

[list(itertools.chain.from_iterable([list[x] for list in list_])) for x in len(one)]

Upvotes: 1

rawwar
rawwar

Reputation: 4992

the following code will scale

from itertools import chain
out = []
for each in zip(*list_):
    out.append(list(chain.from_iterable(each)))

Or a single liner

print([list(chain.from_iterable(each)) for each in zip(*list_)])

Upvotes: 3

Related Questions