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

a = []

如何检查a是否为空?


当前回答

Pythonic的做法来自PEP8风格指南。

对于序列(字符串、列表、元组),请使用空序列为false的事实:#正确:如果不是seq:如果seq:#错误:如果len(seq):如果不是len(seq):

其他回答

print('not empty' if a else 'empty')

更实用一点:

a.pop() if a else None

最短版本:

if a: a.pop() 

让我来到这里的是一个特殊的用例:我实际上想要一个函数来告诉我列表是否为空。我想避免在这里编写自己的函数或使用lambda表达式(因为它看起来应该足够简单):

foo = itertools.takewhile(is_not_empty, (f(x) for x in itertools.count(1)))

当然,有一种非常自然的方法:

foo = itertools.takewhile(bool, (f(x) for x in itertools.count(1)))

当然,不要在if(即if bool(L):)中使用bool,因为它是隐含的。但是,对于明确需要“不为空”作为函数的情况,bool是最佳选择。

Pythonic的做法来自PEP8风格指南。

对于序列(字符串、列表、元组),请使用空序列为false的事实:#正确:如果不是seq:如果seq:#错误:如果len(seq):如果不是len(seq):

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

从python3开始,您可以使用

a == []

检查列表是否为空

编辑:这也适用于python2.7。。

我不知道为什么有这么多复杂的答案。这很清楚明了