cgreen
cgreen

Reputation: 361

Concatenate multiple lists of lists in python

I have a list of multiple list-of-lists in python:

a = [[[0,1,2], [10,11,12]],
     [[3,4,5], [13,14,15]]]

And I would like to merge all the first lists together, the second lists together, and so forth:

final = [[0,1,2,3,4,5],
         [10,11,12,13,14,15]]

The furthest I've got is to try to unzip the outer lists:

zip(*a) = [([0,1,2], [3,4,5]), 
           ([10,11,12], [13,14,15])]

I suppose one could loop through these and then chain each together, but that seems wasteful. What's a pythonic way to fix this?

NOTE: There might be more than two sublists in each "row".

Upvotes: 3

Views: 1273

Answers (2)

FatihAkici
FatihAkici

Reputation: 5109

The reduce function is the perfect fit for this kind of problems:

[reduce((lambda x,y: x[i]+y[i]), a) for i,_ in enumerate(a)]

Result:

[[0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15]]

This code reads: For each index i, collect all the ith items of the elements of a together.

Upvotes: 1

alecxe
alecxe

Reputation: 474001

A combination of zip() and itertools.chain() would do it:

In [1]: from itertools import chain

In [2]: [list(chain(*lists)) for lists in zip(*a)]
Out[2]: [[0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15]]

Upvotes: 3

Related Questions