使用 Python 检查列表中的任何项目是否为 None

使用 in 运算符检查列表中的任何项目是否为 None,例如 if None in my_list:。 in 运算符测试成员资格。 例如,如果 x 是 l 的成员,则 ·x in l· 的计算结果为 True,否则计算结果为 False

my_list = ['a', 'b', None, 'c']

# ✅ check if any item in the list is None
if None in my_list:
    # 👇️ this runs
    print('There is a None value in the list')

# ✅ check if all items in the list are None (or list is empty)
if all(i is None for i in my_list):
    print('all items in the list are None')

第一个 if 语句检查列表中的任何项目是否为 None,第二个 – 如果列表仅包含 None 值。

in 运算符测试成员资格。

my_list = ['a', 'b', None, 'c']

print(None in my_list)  # 👉️ True

print('hello' in my_list)  # 👉️ False

如果 x 是 l 的成员,则 x in l 的计算结果为 True。

x not in l 返回 x in l 的否定。

或者,我们可以使用 any() 函数。

my_list = ['a', 'b', None, 'c']

if any(item is None for item in my_list):
    # 👇️ this runs
    print('list contains a None value')

any 函数将一个可迭代对象作为参数,如果可迭代对象的任何元素为真,则返回 True。

my_list = ['a', 'b', None, 'c']

# 👇️ True
print(any(item is None for item in my_list))

如果可迭代对象为空或可迭代对象中的所有元素都不为真,则 any 函数返回 False。

我们将生成器表达式传递给 any() 函数。

生成器表达式用于对每个元素执行一些操作,或者选择满足条件的元素子集。

在示例中,我们检查每个项目是否为 None 并返回结果。 如果条件至少满足一次,any() 函数将返回 True。