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

a = []

如何检查a是否为空?


当前回答

来自真实值测试的文档:

此处列出的值以外的所有值均视为True

没有一个错误任何数字类型的零,例如0、0.0、0j。任何空序列,例如“”、()、[]。任何空映射,例如{}。如果类定义了__bool_()或__len__()方法,则该方法返回整数零或布尔值False。

可以看出,空列表[]是错误的,因此对布尔值执行操作听起来最有效:

if not a:
    print('"a" is empty!')

其他回答

我更喜欢以下内容:

if a == []:
   print "The list is empty."
def list_test (L):
    if   L is None  : print('list is None')
    elif not L      : print('list is empty')
    else: print('list has %d elements' % len(L))

list_test(None)
list_test([])
list_test([1,2,3])

有时单独测试无和空是很好的,因为这是两种不同的状态。上述代码产生以下输出:

list is None 
list is empty 
list has 3 elements

虽然没有一件事是假的,但这毫无价值。所以,如果你不想单独测试“无”,你不必这么做。

def list_test2 (L):
    if not L      : print('list is empty')
    else: print('list has %d elements' % len(L))

list_test2(None)
list_test2([])
list_test2([1,2,3])

预期产量

list is empty
list is empty
list has 3 elements

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

在真值测试中,空列表本身被认为是错误的(请参见python文档):

a = []
if a:
     print("not empty")

达伦·托马斯的回答:

编辑:反对测试的另一点空列表为False:多态性?你不应该依赖列表是列表。它应该只是像鸭子一样呱呱叫-你怎么样让你的duckCollection呱呱叫当它没有元素时为“False”?

duckCollection应该实现__nonzero_或__len__,因此if-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)多次调用它。