Python - Extracting inner most lists

后端 未结 3 736
逝去的感伤
逝去的感伤 2021-01-01 13:35

Just started toying around with Python so please bear with me :)

Assume the following list which contains nested lists:

[[[[[1, 3, 4, 5]], [1, 3, 8]]         


        
3条回答
  •  -上瘾入骨i
    2021-01-01 13:55

    Using itertools.chain.from_iterable:

    from itertools import chain
    
    def get_inner_lists(xs):
        if isinstance(xs[0], list): # OR all(isinstance(x, list) for x in xs)
            return chain.from_iterable(map(get_inner_lists, xs))
        return xs,
    

    used isinstance(xs[0], list) instead of all(isinstance(x, list) for x in xs), because there's no mixed list / empty inner list.


    >>> list(get_inner_lists([[[[[1, 3, 4, 5]], [1, 3, 8]], [[1, 7, 8]]], [[[6, 7, 8]]], [9]]))
    [[1, 3, 4, 5], [1, 3, 8], [1, 7, 8], [6, 7, 8], [9]]
    

提交回复
热议问题