检查多个变量是否具有相同的值 [英] Check if multiple variables have the same value
问题描述
我有一组三个变量 x、y、z,我想检查它们是否都共享相同的值.在我的情况下,该值将是 1 或 0,但我只需要知道它们是否都相同.目前我正在使用
I have a set of three variables x, y, z and I want to check if they all share the same value. In my case, the value will either be 1 or 0, but I only need to know if they are all the same. Currently I'm using
if 1 == x and 1 == y and 1 == z:
sameness = True
寻找我找到的答案:
if 1 in {x, y, z}:
然而,这作为
if 1 == x or 1 == y or 1 == z:
atleastOneMatch = True
是否可以检查每个:x、y 和 z 中是否为 1?更好的是,是否有更简洁的方法来简单地检查 x、y 和 z 是否相同?
Is it possible to check if 1 is in each: x, y, and z? Better yet, is there a more concise way of checking simply if x, y, and z are the same value?
(如果重要的话,我使用 Python 3.)
(If it matters, I use Python 3.)
推荐答案
如果您有任意序列,请使用 all()
函数 带有生成器表达式:
If you have an arbitrary sequence, use the all()
function with a generator expression:
values = [x, y, z] # can contain any number of values
if all(v == 1 for v in values):
否则,只需对所有三个变量使用==
:
if x == y == z == 1:
如果您只需要知道它们是否都是相同的值(无论是什么值),请使用:
If you only needed to know if they are all the same value (regardless of what value that is), use:
if all(v == values[0] for v in values):
或
if x == y == z:
这篇关于检查多个变量是否具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!