例如,如果通过以下步骤:
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)多次调用它。
简单的方法是检查长度是否等于零。
if len(a) == 0:
print("a is empty")
为什么要检查?
似乎没有人回答过你首先需要测试列表的问题。因为您没有提供额外的上下文,我可以想象,您可能不需要首先执行此检查,但不熟悉Python中的列表处理。
我认为,最Python的方法是根本不检查,而只是处理列表。这样,无论是空的还是满的,它都会做正确的事情。
a = []
for item in a:
# <Do something with item>
# <The rest of code>
这有利于处理的任何内容,同时不需要对空性进行特定检查。如果a为空,则依赖块将不执行,解释器将进入下一行。
如果确实需要检查数组是否为空:
a = []
if not a:
# <React to empty list>
# <The rest of code>
足够了。
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
方法1(首选):
if not a:
print ("Empty")
方法2:
if len(a) == 0:
print("Empty")
方法3:
if a == []:
print ("Empty")