如何针对单个值测试多个变量? [英] How to test multiple variables against a single value?
问题描述
我正在尝试创建一个函数,将多个变量与一个整数进行比较并输出一个由三个字母组成的字符串.我想知道是否有办法将其翻译成 Python.所以说:
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")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")
这将返回一个列表:
["c", "d", "f"]
这样的事情有可能吗?
推荐答案
你误解了布尔表达式的工作原理;它们不像英语句子那样工作,并且猜测您在这里谈论的是所有名称的相同比较.您正在寻找:
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
和 y
否则会自行计算(False
if 0
, True
否则).
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
您可以使用针对元组:
if 1 in (x, y, z):
或者更好:
if 1 in {x, y, z}:
使用一个set
恒定成本成员资格测试的优势(即 in
需要固定的时间,无论左侧操作数是什么).
using a set
to take advantage of the constant-cost membership test (i.e. in
takes a fixed amount of time whatever the left-hand operand is).
当您使用 或
时,python 将运算符的每一侧视为 单独的 表达式.表达式 x or y == 1
首先被视为 x
的布尔测试,然后如果它是 False,则表达式 y == 1
> 已经过测试.
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.
这是由于运算符优先级.or
运算符的优先级低于 ==
测试,因此后者被评估first.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
然而,即使 不是,表达式 x or y or z == 1
实际上被解释为 (x or y orz) == 1
相反,这仍然不会做你期望它做的事情.
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
将评估为真实"的第一个参数,例如不是 False
、数字 0 或空(参见 boolean表达式 详细了解 Python 在布尔上下文中认为 false 的内容).
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).
所以对于值 x = 2;y = 1;z = 0
, x or y or z
将解析为 2
,因为这是参数中第一个类似真值的值.那么 2 == 1
将是 False
,即使 y == 1
将是 True
.
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
.
同样适用于逆;针对单个变量测试多个值;x == 1 or 2 or 3
也会因为同样的原因而失败.使用 x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
这篇关于如何针对单个值测试多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!