Concatenate multiple lists of lists in python

独自空忆成欢 提交于 2019-12-10 19:13:06

问题


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".


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/48086820/concatenate-multiple-lists-of-lists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!