Python: How to check if a nested list is essentially empty?

前端 未结 7 1608
栀梦
栀梦 2020-12-29 05:56

Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by

相关标签:
7条回答
  • 2020-12-29 06:23

    If you do not need to iterate through the lists, simpler is better, so something like this will work:

    def empty_tree(input_list):
        """Recursively iterate through values in nested lists."""
        for item in input_list:
            if not isinstance(item, list) or not empty_tree(item):
                 return False
        return True
    

    However, it would be good to separate the recursive iteration that you will most probably reuse elsewhere and checking that it returns no elements. This way if the mechanism of iteration changes you need to implement the change in one place. For instance when you need to support arbitrary nested iterables, or nested dicts.

    def flatten(input_list):
        """Recursively iterate through values in nested lists."""
        for item in input_list:
            if isinstance(item, list): # Use what ever nesting condition you need here
                for child_item in flatten(item):
                    yield child_item
            else:
                yield item
    
    def has_items(seq):
        """Checks if an iterator has any items."""
        return any(1 for _ in seq)
    
    if not has_items(flatten(my_list)):
        pass
    
    0 讨论(0)
提交回复
热议问题