d.p*_*tto 6 python python-2.7 python-3.x
考虑这个简单的功能
def foo(l=[]):
if not l: print "List is empty"
else : print "List is not empty"
Run Code Online (Sandbox Code Playgroud)
现在让我们打电话给foo
x=[]
foo(x)
#List is empty
foo('')
#List is empty
Run Code Online (Sandbox Code Playgroud)
但如果x = [''],则列表不被视为空!
x=['']
foo(x)
#List is not empty
Run Code Online (Sandbox Code Playgroud)
问题 -
为什么空值列表不被视为空?(在变量的情况下,它被认为是空的,例如)
x=''
if x:print 'not empty!!'
else: print 'empty'
Run Code Online (Sandbox Code Playgroud)如何修改函数foo(),以便列表将在所有这些情况下被视为空:x=[],x=[''],x=['', '']
Chr*_*tts 13
使用内置 any()
def foo(l=[]):
if any(l):
print 'List is not empty'
else:
print 'List is empty'
foo([''])
# List is empty
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4505 次 |
| 最近记录: |