我有这个列表:
li = [{}]
if li:
print 'yes'
#Output - yes
我错误地认为它不会输出任何东西,因为它是一个空洞的东西(虚假(。现在,我该如何检查它的空性?
如果[{}]
是您唯一的情况,则any([{}])
返回False
。但是,它还将为可能不是您想要的[0]
返回False
,并且它将返回True
[[{}]]
。
如果要以递归方式检查列表是否仅包含空项,请尝试以下操作:
def is_empty_recursive(collection):
try:
if len(collection) == 0:
return True
except TypeError:
# This will happen if collection is not a collection for example len(0) will cause this exception
return False
return all(is_empty_recursive(item) for item in collection)
现在你可以像使用它一样
li = [{}]
if not is_empty_recursive(li):
print("yes")
要检查空性,您可以查看列表中包含的每个内容:
emptydict = [{}]
for obj in emptydict:
if obj:
print("yes")
else:
print("no")
要理解为什么集合以某种方式运行,你可以简要回顾集合论(所有集合的集合包含自身吗?(:
https://en.wikipedia.org/wiki/Universal_set
有多种方法,具体取决于您要实现的目标。您可以简单地使用:
li = []
print(li)
如果什么都不返回,那里就什么都没有。