Python 如何检查多个变量与一个值的关系

Python 如何检查多个变量与一个值的关系

变量是存储不同值的实体。当我们分配新值时,每次都会用新值替换前一个值。在Python中,变量可以是字母、下划线、以字母开头的数字值等。多个变量可以与一个值进行比较,可以通过以下方法在Python中进行检查。

使用逻辑运算符’or’和’and’

在Python中,一种检查多个变量与一个值的方法是使用逻辑运算符’or’和’and’。’and’运算符将检查所有变量是否等于其对应的值,’or’运算符将检查任何一个变量是否等于其对应的值。

示例

在这个例子中,我们将使用’and’运算符来检查所有定义的变量是否等于其对应的值。以下是可以作为参考的代码。

a = 300
b = 400
c = 10
if a == b and b == c and c == a:
    print("All the variables are equal to their respective values")
else:
    print("All the variables are not equal to their respective values")

输出

下面是使用 and 运算符检查所有多个变量是否等于它们各自的值的输出结果。

All the variables are not equal to their respective values

示例

在这个示例中,我们将使用 or 运算符来检查至少一个变量是否等于其相应的值。

a = 300
b = 10
c = 10
if a == b or b == c or c == a:
    print("All the variables are equal to their respective values")
else:
    print("All the variables are not equal to their respective values")

输出

All the variables are equal to their respective values

使用变量列表

另一种方法是通过使用Python的 all() 函数和 any() 函数检查给定变量是否等于其相应的值。

all() 函数将检查给定变量的所有值是否相等,而 any() 函数将检查至少一个变量是否等于其相应的值。

示例

在这里,我们将向 all() 函数传递带有值的变量列表,然后它将返回文本,指示所有变量是否等于其相应的值。

a = 300
b = 10
c = 10
if all([a == 300,b == 10,c == 10]):
    print("All the variables are equal to their respective values")
else:
    print("All the variables are not equal to their respective values")

输出

All the variables are equal to their respective values

示例

让我们来看另一个使用 any() 函数来检查至少有一个变量是否等于其相应值的示例。

a = 300
b = 10
c = 10
if any([a == 0,b == 0,c == 0]):
    print("At least one variable is equal to their respective values")
else:
    print("All the variables are not equal to their respective values")

输出

All the variables are not equal to their respective values

使用字典

在这种方式中,我们将使用字典将变量保存为键,将它们对应的值保存为值。在这里,我们使用列表推导和locals()函数来检查字典中的所有变量或至少一个变量是否等于其对应的值。locals()函数用于过滤字典中的变量。

示例

在这个示例中,我们将使用列表推导和locals()函数来检查字典中的所有变量是否等于它们对应的值。

a = 300
b = 20
c = 30
d = 340
dic = {"a" : 10,"b" : 20,"c" : 40,"d" : 230}
if all([dic[key] == value for key, value in locals().items() if key in dic]):
    print("All the variables are equal to their respective values")
else:
     print("All the variables are not equal to their respective values")

输出

All the variables are not equal to their respective values

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程