例如,如果通过以下步骤:
a = []
如何检查a是否为空?
例如,如果通过以下步骤:
a = []
如何检查a是否为空?
当前回答
我更喜欢以下内容:
if a == []:
print "The list is empty."
其他回答
我更喜欢以下内容:
if a == []:
print "The list is empty."
print('not empty' if a else 'empty')
更实用一点:
a.pop() if a else None
最短版本:
if a: a.pop()
在真值测试中,空列表本身被认为是错误的(请参见python文档):
a = []
if a:
print("not empty")
达伦·托马斯的回答:
编辑:反对测试的另一点空列表为False:多态性?你不应该依赖列表是列表。它应该只是像鸭子一样呱呱叫-你怎么样让你的duckCollection呱呱叫当它没有元素时为“False”?
duckCollection应该实现__nonzero_或__len__,因此if-a:将毫无问题地工作。
受到dubiusjim解决方案的启发,我建议使用一个额外的常规检查,看看它是否可以迭代:
import collections
def is_empty(a):
return not a and isinstance(a, collections.Iterable)
注意:如果希望排除空字符串,则字符串被认为是可迭代的add,而不是isinstance(a,(str,unicode))
测试:
>>> is_empty('sss')
False
>>> is_empty(555)
False
>>> is_empty(0)
False
>>> is_empty('')
True
>>> is_empty([3])
False
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(())
True
if not a:
print("List is empty")
使用空列表的隐含布尔性是相当Python的。