如何针对值测试多个变量? [英] How to test multiple variables against a value?

查看:123
本文介绍了如何针对值测试多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将多个变量与一个整数进行比较并输出三个字母的字符串的函数。我想知道是否有办法将其转换为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 如果 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}:

使用 设置 利用恒定成本会员资格测试(无论左手操作数是什么,中的需要一定的时间)。

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).

当您使用时,python会将运算符的每一侧视为单独的表达式。表达式 x或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.

这是由于运算符优先级运算符的优先级低于 == 测试,因此后者首先被评估

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

然而,即使这是的情况,表达式 x或y或z = = 1 实际上被解释为(x或y或z)== 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或y或z 将评估为'truthy'的第一个参数,例如:不是 False ,数字0或空(参见布尔表达式,以获取有关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或y或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或2或3 会因同样的原因失败。在{1,2,3}中使用 x == 1或x == 2或x == 3 x

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆