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

Phi*_*ham 6 python types list

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

我明白我可以测试:

if MyList:
    pass
Run Code Online (Sandbox Code Playgroud)

和:

if not MyList:
    pass
Run Code Online (Sandbox Code Playgroud)

但是如果列表有一个项目(或多个项目),但那些项目是无:

MyList = [None, None, None]
if ???:
    pass
Run Code Online (Sandbox Code Playgroud)

Ste*_*202 15

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

if all(e is None for e in myList):
    print('all empty or None')
Run Code Online (Sandbox Code Playgroud)

这也适用于空列表.更一般地,为了测试列表是否仅包含评估的内容False,您可以使用any:

if not any(myList):
    print('all empty or evaluating to False')
Run Code Online (Sandbox Code Playgroud)

  • 如果`type(x).__ eq __()`被破坏,使用==*可能是错误的. (5认同)
  • 它应该是"e is None". (2认同)

小智 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
Run Code Online (Sandbox Code Playgroud)