gpt4 book ai didi

python-3.x - python如何检查列表不包含任何值

转载 作者:太空狗 更新时间:2023-10-29 22:05:04 25 4
gpt4 key购买 nike

考虑这个简单的函数

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

问题-

  1. 为什么空值列表不被视为空? (在变量的情况下,它被认为是空的,例如)

    x=''
    if x:print 'not empty!!'
    else: print 'empty'
  2. 如何修改函数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com