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

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

    Because this question looks fun!
    I used a recursive function that unpacks a list if it only has one value.

    def make_singular(l):
        try:
            if len(l) == 1:
                return l[0]
            else:
                return [make_singular(l_) for l_ in l]
        except:
            return l
    
    nest = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]
    make_singular(nest)
    
    [[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]
    

提交回复
热议问题