例如,如果通过以下步骤:
a = []
如何检查a是否为空?
例如,如果通过以下步骤:
a = []
如何检查a是否为空?
当前回答
方法1(首选):
if not a:
print ("Empty")
方法2:
if len(a) == 0:
print("Empty")
方法3:
if a == []:
print ("Empty")
其他回答
以下是检查列表是否为空的几种方法:
a = [] #the list
1) 非常简单的蟒蛇方式:
if not a:
print("a is empty")
在Python中,空容器(如列表、元组、集合、字典、变量等)被视为False。可以简单地将列表视为谓词(返回布尔值)。True值表示它为非空。
2) 一种非常明确的方法:使用len()查找长度并检查它是否等于0:
if len(a) == 0:
print("a is empty")
3) 或者将其与匿名空列表进行比较:
if a == []:
print("a is empty")
4) 另一种愚蠢的方法是使用exception和iter():
try:
next(iter(a))
# list has elements
except StopIteration:
print("Error: a is empty")
方法1(首选):
if not a:
print ("Empty")
方法2:
if len(a) == 0:
print("Empty")
方法3:
if a == []:
print ("Empty")
让我来到这里的是一个特殊的用例:我实际上想要一个函数来告诉我列表是否为空。我想避免在这里编写自己的函数或使用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是最佳选择。
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
只需使用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)多次调用它。