例如,如果通过以下步骤:
a = []
如何检查a是否为空?
例如,如果通过以下步骤:
a = []
如何检查a是否为空?
当前回答
if not a:
print("List is empty")
使用空列表的隐含布尔性是相当Python的。
其他回答
只需使用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)多次调用它。
受到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
已经给出了很多答案,其中很多都很好。我只是想加上那张支票
not a
也将通过None和其他类型的空结构。如果您确实想检查空列表,可以执行以下操作:
if isinstance(a, list) and len(a)==0:
print("Received an empty list")
如果要检查列表是否为空:
l = []
if l:
# do your stuff.
如果要检查列表中的所有值是否为空。然而,空列表将为True:
l = ["", False, 0, '', [], {}, ()]
if all(bool(x) for x in l):
# do your stuff.
如果要同时使用这两种情况:
def empty_list(lst):
if len(lst) == 0:
return False
else:
return all(bool(x) for x in l)
现在您可以使用:
if empty_list(lst):
# do your stuff.
简单的方法是检查长度是否等于零。
if len(a) == 0:
print("a is empty")