flatten list of lists of lists to a list of lists

前端 未结 4 1425
耶瑟儿~
耶瑟儿~ 2020-12-07 03:27

I\'ve already searched SO for how to flatten a list of lists (i.e. here:Making a flat list out of list of lists in Python) but none of the solutions I find addresses flatten

4条回答
  •  爱一瞬间的悲伤
    2020-12-07 03:59

    This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after:

    def flatten(lists,n):
        if n == 1:
            return [x for xs in lists for x in xs]   
        else:
            return [flatten(xs,n-1) for xs in lists]
    
    
    >>> flatten(my_list,1)
    [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
    >>> flatten(my_list,2)
    [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
    

提交回复
热议问题