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

a = []

如何检查a是否为空?


当前回答

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

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

其他回答

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

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

如果要检查列表是否为空:

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(li) == 0:
    print('the list is empty')

通过这种方式,可以100%清楚地看出li是一个序列(列表),我们想测试它的大小。我的问题,如果不是李:。。。这给人一种错觉,认为li是一个布尔变量。

您甚至可以尝试像这样使用bool()。虽然它的可读性较低,但它确实是一种简洁的方法。

    a = [1,2,3];
    print bool(a); # it will return True
    a = [];
    print bool(a); # it will return False

我喜欢这种方式,因为检查列表是否为空。

非常方便和有用。

只需使用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)多次调用它。