检查列表是否为空或仅包含无的最简洁的方法? [英] Most concise way to check whether a list is empty or contains only None?

查看:68
本文介绍了检查列表是否为空或仅包含无的最简洁的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简洁的方法来检查列表是否为空或仅包含无?

Most concise way to check whether a list is empty or contains only None?

我知道我可以测试:

if MyList:
    pass

和:

if not MyList:
    pass

但是如果列表中有一个(或多个)项目,但这些项目为None,该怎么办?

but what if the list has an item (or multiple items), but those item/s are None:

MyList = [None, None, None]
if ???:
    pass

推荐答案

一种方法是使用

One way is to use all and a list comprehension:

if all(e is None for e in myList):
    print('all empty or None')

这也适用于空列表.更一般而言,要测试列表是否仅包含评估为False的内容,可以使用

This works for empty lists as well. More generally, to test whether the list only contains things that evaluate to False, you can use any:

if not any(myList):
    print('all empty or evaluating to False')

这篇关于检查列表是否为空或仅包含无的最简洁的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆