例如,如果通过以下步骤:
a = []
如何检查a是否为空?
例如,如果通过以下步骤:
a = []
如何检查a是否为空?
当前回答
print('not empty' if a else 'empty')
更实用一点:
a.pop() if a else None
最短版本:
if a: a.pop()
其他回答
print('not empty' if a else 'empty')
更实用一点:
a.pop() if a else None
最短版本:
if a: a.pop()
您甚至可以尝试像这样使用bool()。虽然它的可读性较低,但它确实是一种简洁的方法。
a = [1,2,3];
print bool(a); # it will return True
a = [];
print bool(a); # it will return False
我喜欢这种方式,因为检查列表是否为空。
非常方便和有用。
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
为什么要检查?
似乎没有人回答过你首先需要测试列表的问题。因为您没有提供额外的上下文,我可以想象,您可能不需要首先执行此检查,但不熟悉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>
足够了。
if not a:
print("List is empty")
使用空列表的隐含布尔性是相当Python的。