考虑这个简单的函数
def foo(l=[]):
if not l: print "List is empty"
else : print "List is not empty"
现在让我们调用 foo
x=[]
foo(x)
#List is empty
foo('')
#List is empty
但是如果 x=[''] 列表不被认为是空的!!!
x=['']
foo(x)
#List is not empty
问题-
为什么空值列表不被视为空? (在变量的情况下,它被认为是空的,例如)
x='' if x:print 'not empty!!' else: print 'empty'
如何修改函数 foo() 以便在所有这些情况下列表都被视为空:
x=[]
,x=['']
,x=['', '']
最佳答案
使用内置的any()
def foo(l=[]):
if any(l):
print 'List is not empty'
else:
print 'List is empty'
foo([''])
# List is empty
关于python-3.x - python如何检查列表不包含任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191264/