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

前端 未结 7 1467
感情败类
感情败类 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

    If the nesting is always consistent, then this is trivial:

    In [2]: import itertools
    
    In [3]: nested = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]
    
    In [4]: unested = [list(itertools.chain(*sub)) for sub in nested]
    
    In [5]: unested
    Out[5]: [[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]
    

    Note, the solutions that leverage add with lists are going to give you O(n^2) performance where n is the number of sub-sublists that are being merged within each sublist.

提交回复
热议问题