How to remove something from a list with recursion? Python

前端 未结 1 1912
南笙
南笙 2021-01-23 16:51

I have this exercise:

You have a tree graph as input, and you need to remove its leaves. So you need to remove the empty lists from a list of lists.

For example

相关标签:
1条回答
  • 2021-01-23 17:13

    The solution:

    def tree_cut(tree):
        return [tree_cut(x) for x in tree if x]
    

    uses a list comprehension to iterate, filter and transform nodes in the tree.

    Can be written also in terms of map() and filter():

    def tree_cut(tree):
        return list(map(tree_cut, filter(None, tree)))
    

    The if x part tests if the list is not empty.

    >>> tree = [[[[], []], [[], []]], [[], [], []]]
    >>> tree_cut(tree)
    [[[], []], []]
    
    0 讨论(0)
提交回复
热议问题