最简洁的方法来检查列表是空的还是只包含None?
我明白我可以测试:
if MyList:
    pass
和:
if not MyList:
    pass
但是如果列表有一个项目(或多个项目),但那些项目是无:
MyList = [None, None, None]
if ???:
    pass
Ste*_*202 15
一种方法是使用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')
小智 9
您可以使用该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