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

标签 python-3.x python-2.7 python

考虑这个简单的函数

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/

相关文章:

python-3.x - 如何模拟 "async with"语句?

python - 如何从 pandas 数据框中获取同一行(前一列)的前一个值?

python - 将 JSON 值添加到列表中

python - 删除比预期更多的字符

python - Matplotlib:cbar.set_xticklabels 没有效果

python - Unorderable Type 错误在 Python 中意味着什么?

json - 如何在 python 中迭代 json 树

python - Python 中 "def"后面的字符串是什么? (不是文档字符串)

python - 将时间转换为人类可读格式的 Shell 脚本或 Python 脚本

Python执行windows cmd函数