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

前端 未结 7 1606
栀梦
栀梦 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:05

    Simple code, works for any iterable object, not just lists:

    >>> def empty(seq):
    ...     try:
    ...         return all(map(empty, seq))
    ...     except TypeError:
    ...         return False
    ...
    >>> empty([])
    True
    >>> empty([4])
    False
    >>> empty([[]])
    True
    >>> empty([[], []])
    True
    >>> empty([[], [8]])
    False
    >>> empty([[], (False for _ in range(0))])
    True
    >>> empty([[], (False for _ in range(1))])
    False
    >>> empty([[], (True for _ in range(1))])
    False
    

    This code makes the assumption that anything that can be iterated over will contain other elements, and should not be considered a leaf in the "tree". If an attempt to iterate over an object fails, then it is not a sequence, and hence certainly not an empty sequence (thus False is returned). Finally, this code makes use of the fact that all returns True if its argument is an empty sequence.

提交回复
热议问题