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

问题描述:

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

我知道我可以测试:

if MyList: 
    pass 

和:

if not MyList: 
    pass 

但如果该列表中有一个项目(或多个项目),但是这些项目/ s为无:

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

的一种方法是使用all和列表理解:

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

这适用于空列表为好。更一般地,以测试列表是否只包含的东西,计算结果为False,您可以使用any

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

它应该是'e is None'。 – nikow 2009-08-13 10:01:04

+0

这可能更有效率,是的,但使用'=='不是*错误*。 – Stephan202 2009-08-13 10:17:25

+0

小记:所有的链接实际上是任何... – 2009-08-13 11:11:22

如果您关注列表中评估为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" 

如果要严格检查None,在if上述声明使用filter(lambda x: x is not None, mylist)代替filter(None, mylist)

可以使用all()功能测试是所有元​​素都是无:

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

你可以直接与==比较列表:

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

if x == [1,2,3]