简体   繁体   English

最简洁的方法来检查列表是空的还是只包含None?

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

Most concise way to check whether a list is empty or contains only None? 最简洁的方法来检查列表是空的还是只包含None?

I understand that I can test: 我明白我可以测试:

if MyList:
    pass

and: 和:

if not MyList:
    pass

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: 一种方法是使用all和list comprehension:

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

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 : 更一般地,要测试列表是否仅包含评估为False ,您可以使用any

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

You can use the all() function to test is all elements are None: 你可以使用all()函数来测试所有元素都是None:

a = []
b = [None, None, None]
all(e is None for e in a) # True
all(e is None for e in b) # True

You can directly compare lists with == : 您可以直接将列表与==进行比较:

if x == [None,None,None]:

if x == [1,2,3]

If you are concerned with elements in the list which evaluate as true: 如果您关注列表中评估为true的元素:

if mylist and filter(None, mylist):
    print "List is not empty and contains some true values"
else:
    print "Either list is empty, or it contains no true values"

If you want to strictly check for None , use filter(lambda x: x is not None, mylist) instead of filter(None, mylist) in the if statement above. 如果要严格检查None ,请在上面的if语句中使用filter(lambda x: x is not None, mylist)而不是filter(None, mylist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM