flatten list of list through list comprehension

前端 未结 5 738
闹比i
闹比i 2020-12-01 21:15

I am trying to flatten a list using list comprehension in python. My list is somewhat like

[[1, 2, 3], [4, 5, 6], 7, 8]

just for printing

5条回答
  •  [愿得一人]
    2020-12-01 21:51

    def nnl(nl):    # non nested list
    
        nn = []
    
        for x in nl:
            if type(x) == type(5):
                nn.append(x)
    
        if type(x) == type([]):
            n = nnl(x)
    
            for y in n:
                nn.append(y)
        return nn
    
    print (nnl([[9, 4, 5], [3, 8,[5]], 6]))  # output: [9, 4, 5, 3, 8, 5, 6]
    

提交回复
热议问题