如何对多个值测试一个变量? [英] How do I test one variable against multiple values?
问题描述
我试图创建一个函数,将多个变量比较一个整数,并输出一个三个字母的字符串。我想知道是否有一种方法来将它翻译成Python。所以说:
x = 0
y = 1
z = 3
Mylist = []
如果x或y或z == 0:
Mylist.append(c)
elif x或y或z == 1:
Mylist。 append(d)
elif x或y或z == 2:
Mylist.append(e)
elif x或y或z == 3:
Mylist.append(f)
会返回
[c,d,f]
$ b
你误解了布尔表达式是如何工作的?他们不像英语句子那样工作,并猜测你在这里对所有名字都进行了相同的比较。您正在寻找:
如果x == 1或y == 1或z == 1:
x
和 y
否则自己评估( False
如果 0
, True $
<$ c $ <$ p> c> if(x,y,z)中的1:
如果在{x,y,z}中为1:
使用设置
以利用常量成本测试( in
当使用或
时,python将操作符的每一侧视为独立的表达式。表达式 x或y == 1
被视为首先对 x
的布尔检验,如果是False,
这是由于 docs.python.org/2/reference/expressions.html#operator-precedence\">运算符优先顺序。 或
运算符的优先级比 ==
测试的优先级低,因此,
x或y或z = = 1
实际上被解释为(x或y或z)== 1
,但这仍然不会做你期望的做。 x或y或z
会计算第一个参数为truey不是 False
,数字0或空(请参阅布尔表达式,以了解Python在布尔上下文中认为是什么的细节。)
所以对于 x = 2; y = 1; z = 0
, x或y或z
会解析为 2
参数中的第一个真实值。那么 2 == 1
将是 False
,即使 y == 1
将 True
。
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.append("c")
elif x or y or z == 1 :
Mylist.append("d")
elif x or y or z == 2 :
Mylist.append("e")
elif x or y or z == 3 :
Mylist.append("f")
which would return a list of
["c", "d", "f"]
Is something like this possible?
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that to:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (in
takes a fixed amount of time whatever the left-hand operand is).
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
这篇关于如何对多个值测试一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!