Python - Extracting inner most lists

后端 未结 3 941
失恋的感觉
失恋的感觉 2021-01-01 13:11

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条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 13:56

    This seems to work, assuming no 'mixed' lists like [1,2,[3]]:

    def get_inner(nested):
        if all(type(x) == list for x in nested):
            for x in nested:
                for y in get_inner(x):
                    yield y
        else:
            yield nested
    

    Output of list(get_inner(nested_list)):

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

    Or even shorter, without generators, using sum to combine the resulting lists:

    def get_inner(nested):
        if all(type(x) == list for x in nested):
            return sum(map(get_inner, nested), [])
        return [nested]
    

提交回复
热议问题