迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中检查变量是否等于两个值之一

作者:迹忆客 最近更新:2023/01/24 浏览次数:

使用 in 运算符检查变量是否等于两个值之一,例如 if my_str in ('first', 'second'):。 如果变量等于两个值之一,则 in 运算符的计算结果为 True,否则为 False

my_str = 'apple'

two_values = ('kiwi', 'apple')

if my_str in two_values:
    # 👇️ this runs
    print('The variable is equal to one of the two values')
else:
    print('The variable is NOT equal to any of the specified values')


print(my_str in two_values)  # 👉️ True

我们使用 in 运算符来检查变量是否等于两个值之一。

我们将值分组在一个元组中,因此我们可以测试成员资格。

in 运算符测试成员资格。 例如,如果 xt 的成员,则 x in t 的计算结果为 True,否则计算结果为 False

如果变量至少等于其中一个值,则运行 if 块,否则运行 else 块。

my_str = 'apple'

two_values = ('kiwi', 'apple')

print(my_str in two_values)  # 👉️ True

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

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

使用 any() 函数检查变量是否等于两个值之一,例如 if any(my_str == item for item in ('first', 'second')):。 如果变量等于两个值之一,则 any() 函数将返回 True,否则返回 False

my_str = 'apple'

two_values = ('kiwi', 'apple')

if any(my_str == item for item in two_values):
    # 👇️ this runs
    print('The variable is equal to one of the two values')
else:
    print('The variable is NOT equal to any of the specified values')

我们使用生成器表达式来遍历列表。

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

在每次迭代中,我们检查变量是否等于当前值并返回结果。

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

my_str = 'apple'

two_values = ('kiwi', 'apple')

# 👇️ True
print(any(my_str == item for item in two_values))

如果满足条件,any() 函数将短路并返回 True

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

my_str = 'apple'

two_values = ('kiwi', 'banana')

if any(my_str == item for item in two_values):
    print('The variable is equal to one of the two values')
else:
    # 👇️ this runs
    print('The variable is NOT equal to any of the specified values')

# 👇️ False
print(any(my_str == item for item in two_values))

该变量不等于任何指定值,因此条件永远不会满足,else 块将运行。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便