例如,如果通过以下步骤:

a = []

如何检查a是否为空?


当前回答

只需使用is_empty()或生成如下函数:-

def is_empty(any_structure):
    if any_structure:
        print('Structure is not empty.')
        return True
    else:
        print('Structure is empty.')
        return False  

它可以用于任何数据结构,如列表、元组、字典等等。通过这些,您可以使用is_empty(any_structure)多次调用它。

其他回答

if not a:
    print("List is empty")

使用空列表的隐含布尔性是相当Python的。

受到dubiusjim解决方案的启发,我建议使用一个额外的常规检查,看看它是否可以迭代:

import collections
def is_empty(a):
    return not a and isinstance(a, collections.Iterable)

注意:如果希望排除空字符串,则字符串被认为是可迭代的add,而不是isinstance(a,(str,unicode))

测试:

>>> is_empty('sss')
False
>>> is_empty(555)
False
>>> is_empty(0)
False
>>> is_empty('')
True
>>> is_empty([3])
False
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(())
True

简单的方法是检查长度是否等于零。

if len(a) == 0:
    print("a is empty")

已经给出了很多答案,其中很多都很好。我只是想加上那张支票

not a

也将通过None和其他类型的空结构。如果您确实想检查空列表,可以执行以下操作:

if isinstance(a, list) and len(a)==0:
    print("Received an empty list")

空列表的真值为False,而非空列表的值为True。