How to remove the innermost level of nesting in a list of lists of varying lengths

前端 未结 7 1533
感情败类
感情败类 2021-01-13 14:51

I\'m trying to remove the innermost nesting in a list of lists of single element length lists. Do you know a relatively easy way (converting to NumPy arrays is fine) to get

7条回答
  •  既然无缘
    2021-01-13 15:24

    >>> from operator import add
    >>> lists = [ [ [1],[2],[3],[4], [5] ],   [ [6],[7],[8] ] , [ [11],[12] ] ]
    >>> [reduce(add, lst) for lst in lists]
    [[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]
    

    This is not a very efficient, as it rebuilds a list each time add is called. Alternatively you can use sum or a simple list comprehension, as seen in the other answers.

提交回复
热议问题