简体   繁体   中英

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!

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.

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]]

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]]

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM