Dominik K.
Dominik K.

Reputation: 3

Flatten tuples in a nested list

is there a compact oneliner or python idiom to handle the following task?

I want to transform a list of list of tuples like this:

input = [[(1,2,3),(4,5,6)],[(7,8,9),(10,11,12)]]

to this:

output [[1,2,3,7,8,9], [4,5,6,10,11,12]]

Using map and flattening the list only gave me the follwing

input_trans = map(list, zip(*input))
input_trans_flat = [item for sublist in input_trans for item in sublist]
Out: [(1, 2, 3), (7, 8, 9), (4, 5, 6), (10, 11, 12)]

Many Thanks in Advance!

Upvotes: 0

Views: 118

Answers (4)

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

Here's one way.

from itertools import chain
l = [[(1,2,3),(4,5,6)],[(7,8,9),(10,11,12)]]
[list(chain.from_iterable(s)) for s in l]

gives me

[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]

Upvotes: -1

cs95
cs95

Reputation: 402583

You should be able to generalise Blckknght's answer to any number of tuples inside a list, using sum.

output = [list(sum(x, ())) for x in zip(*input)]
print(output)

[[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

Upvotes: 2

ettanany
ettanany

Reputation: 19806

You can use list comprehension with zip() like below:

output = [[item for tup in (i, j) for item in tup] for i, j in zip(*input)]

Output:

>>> input = [[(1, 2, 3), (4, 5, 6)], [(7, 8, 9), (10, 11, 12)]]
>>>
>>> output = [[item for tup in (i, j) for item in tup] for i, j in zip(*input)]
>>> output
[[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

Upvotes: 0

Blckknght
Blckknght

Reputation: 104722

I'd do:

output = [list(a + b) for a, b in zip(*input)]

The zip part, as you already know, transposes the outer list of lists. Then I grab each pair of tuples and concatenate them, then turn the combined tuple into a list. If you don't care if you have a list of lists or a list of tuples in the end, you could get rid of the list call.

Upvotes: 2

Related Questions