Python 中检查多个变量是否不是 None
Python 中检查多个变量是否不是 None:
- 将变量包装在列表中。
- 使用生成器表达式迭代列表。
- 在每次迭代中,检查当前列表项是否不是 None。
- 将生成器对象传递给 all() 函数。
a = 'a'
b = 'b'
c = 'c'
if all(item is not None for item in [a, b, c]):
print('Multiple variables are NOT None')
else:
print('At least one of the variables stores a None value')
我们使用方括号将变量添加到列表中,并使用生成器表达式迭代列表。
在每次迭代中,我们检查当前列表项是否不是 None 并返回结果。
最后一步是将生成器对象传递给 all() 函数。
all() 内置函数接受一个可迭代对象作为参数,如果该可迭代对象的所有元素都为真(或者该可迭代对象为空),则返回 True。
另一种方法是使用 in 运算符。
检查多个变量是否不是 None:
- 将变量包装在一个序列中(例如元组或列表)。
- 使用 not in 运算符检查 None 是否不是序列的成员。
- 如果序列不包含 None,则变量不是 None。
a = 'a'
b = 'b'
c = 'c'
if None not in (a, b, c):
# ?️ this runs
print('Multiple variables are NOT None')
这在 Python 中不是一个好的做法,因为建议使用 is 关键字检查 None 。
in 运算符测试成员资格。 例如,如果 x 是 l 的成员,则 x in l 的计算结果为 True,否则计算结果为 False。
x not in l 返回 x in l 的否定。
另一种方法是多次使用 and 运算符。
a = 'a'
b = 'b'
c = 'c'
if a is not None and b is not None and c is not None:
print('Multiple variables are NOT None')
通常不推荐这样做,因为它非常重复且难以阅读。
if 语句首先检查 a 变量是否不为 None。 如果是,则 if 语句短路返回 False,而不检查以下任何条件。
如果表达式 x 和 y 为假,则返回左边的值,否则返回右边的值。
result = False and 'hello'
print(result) # ?️ False
所有不真实的值都被认为是虚假的。 Python 中的虚假值是:
- 定义为 falsy 的常量:None 和 False。
- 任何数字类型的 0(零)
- 空序列和集合:””(空字符串)、()(空元组)、[](空列表)、{}(空字典)、set()(空集)、range(0)(空范围)。
因此,如果左侧的值是上述任何虚假值,则返回左侧的值。
a = 'a'
b = 'b'
c = 'c'
if all(item is not None for item in [a, b, c]):
print('Multiple variables are NOT None')
else:
print('At least one of the variables stores a None value')
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。