如何在Python中检查多个变量是否与某个值相等?
变量是存储不同值的实体。每次赋值新值时,前一个值都会被新的值替换。在Python中,变量可以是字母、下划线、数字,但必须以字母开头等。可以对多个变量与一个值进行比较;可以使用以下几种方法在Python中进行检查。
使用逻辑“或”和“与”
在Python中检查多个变量是否与某个值相等的一种方法是使用逻辑或和与。与运算符将检查所有变量是否都等于它们各自的值,而或运算符将检查是否有任何一个变量等于其各自的值。
示例
在这个示例中,我们将使用与运算符来检查所有定义的变量是否都等于它们各自的值。以下是可以作为参考的代码。
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")
输出
以下是使用与运算符检查所有多个变量是否都等于它们各自的值的输出。
All the variables are not equal to their respective values
示例
在这个示例中,我们将使用或运算符来检查至少一个变量是否等于其各自的值。
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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP