如何测试多个变量与单个值的相等性?
我正在尝试创建一个函数,将多个变量与一个整数进行比较并输出一个由三个字母组成的字符串。我想知道是否有办法将其翻译成Python。所以说:
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"]
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")
which would return a list of:
["c", "d", "f"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
一行解决方案:
或者:
One line solution:
Or:
也许您需要输出位集的直接公式。
让我们映射到位:
'c':1 'd':0xb10 'e':0xb100 'f':0xb1000
isc 的关系(是 'c'):
使用数学 if 公式 https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315
[c]:
(xyz=0 和 isc=1) 或 (((xyz=0且 isc=1) 或 (isc=0)) 且(isc=0))
[d]:
((x-1)(y-1)(z-1)=0 且 isc=2) 或 (((xyz=0 且 isd= 2) or (isc=0)) and (isc=0))
...
通过以下逻辑连接这些公式:
and
是方程的平方和的乘积
or 是方程和 你将得到一个总方程
表达 sum 并且你有 sum 的总公式
然后 sum&1 是 c,sum&2 是 d,sum&4 是 e,sum&5 是 f
之后,你可以形成预定义的数组,其中字符串元素的索引将对应于准备好的字符串。
array[sum]
为您提供字符串。Maybe you need direct formula for output bits set.
Let's map to bits:
'c':1 'd':0xb10 'e':0xb100 'f':0xb1000
Relation of isc (is 'c'):
Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315
[c]:
(xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))
[d]:
((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))
...
Connect these formulas by following logic:
and
is the sum of squares of equationsor
is the product of equationsand you'll have a total equation
express sum and you have total formula of sum
then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f
After this you may form predefined array where index of string elements would correspond to ready string.
array[sum]
gives you the string.在 Python 中表示伪代码的最 Pythonic 方式是:
The most pythonic way of representing your pseudo-code in Python would be:
这可以很容易地完成
It can be done easily as
使用一个值测试多个变量:
if 1 in {a,b,c}:
使用一个变量测试多个值:
if a in {1, 2, 3}:< /代码>
To test multiple variables with one single value:
if 1 in {a,b,c}:
To test multiple values with one variable:
if a in {1, 2, 3}:
看起来你正在构建某种凯撒密码。
更通用的方法是这样的:
输出
不确定这是否是代码所需的副作用,但输出的顺序将始终被排序。
如果这是你想要的,最后一行可以更改为:
Looks like you're building some kind of Caesar cipher.
A much more generalized approach is this:
outputs
Not sure if it's a desired side effect of your code, but the order of your output will always be sorted.
If this is what you want, the final line can be changed to:
您可以使用字典:
You can use dictionary :
如果没有 dict,请尝试此解决方案:
并给出:
Without dict, try this solution:
and gives:
这会对你有所帮助。
This will help you.
您可以将其合并
到一个变量中。
将我们的条件更改为:
输出:
You can unite this
in one variable.
Change our conditions as:
Output:
你可以通过两种方式开发它
或者
you can develop it through two ways
Or
或
不会像这样工作,正如这个答案所解释的。虽然通用答案是使用,
但这并不是解决特定问题的最佳答案。在您的情况下,您正在执行重复测试,因此值得组合这些变量的集合:
我们可以使用字典来简化它 - 这将导致相同的结果值:
或者,如果
mylist
的顺序是任意的,您可以循环遍历值,并将它们与映射匹配:The
or
does not work like that, as explained by this answer.While the generic answer would be use
this is not the best one for the specific problem. In your case you're doing repeated tests, therefore it is worthwhile to compose a set of these variables:
We can simplify this using a dictionary - this will result in the same values:
Or if the ordering of the
mylist
is arbitrary, you can loop over the values instead and match them to the mappings:问题
虽然测试多个值的模式
非常可读并且在许多情况下都有效,但存在一个陷阱:
但我们希望解决
方案
一对前一个表达式的概括是基于 ytpillai:
可以写成
虽然这个表达式返回正确的结果,但它的可读性不如第一个表达式:-(
Problem
While the pattern for testing multiple values
is very readable and is working in many situation, there is one pitfall:
But we want to have
Solution
One generalization of the previous expression is based on the answer from ytpillai:
which can be written as
While this expression returns the right result it is not as readable as the first expression :-(
要针对单个值测试多个变量:
将变量包装在集合对象中,例如 {a, b, c}。
使用 in 运算符测试该值是否存储在任何变量中。
如果值至少存储在一个变量中,则 in 运算符将返回 True。
To test multiple variables against a single value:
Wrap the variables in a set object, e.g. {a, b, c}.
Use the in operator to test if the value is stored in any of the variables.
The in operator will return True if the value is stored in at least one of the variables.
这是另一种方法:
它是列表理解和任何关键字的组合。
Here is one more way to do it:
It is a mix of list comprehension and any keyword.
不使用 if 示例的用法:
usage without if example:
首先,对
OR
条件的更正:您需要说:
原因是“or”将条件分成单独的逻辑部分。按照您最初的声明的编写方式,这些部分是:
最后一部分很好 --- 例如检查 z == 0 --- 但前两部分本质上只是说
if x
和如果是
。由于整数的计算结果始终为True
,除非它们为 0,这意味着当x
或时,条件的第一部分始终为
不等于 0(在 y 的情况下总是如此,因为你有True
yy = 1
,导致你的整个情况(因为OR
有效)始终为True
为了避免这种情况,您可以这样做 。需要确保条件的所有部分(
OR
的每一侧)本身都有意义(您可以通过假装OR
的另一侧来做到这一点code> 语句不存在)。这就是您可以确认OR
条件是否正确定义的方法,您可以像这样单独编写语句:
这意味着与
的合并正确 。 OR
关键字将是:SECOND, HOW TO解决问题:
您基本上想要检查是否有任何变量与给定的整数匹配,如果是,则为其分配一个与一对一映射中匹配的字母。您希望对某个整数列表执行此操作,以便输出是字母列表。您可以这样做:
同样,您可以使用 LIST COMPREHENSION 更快地获得相同的结果:
FIRST, A CORRECTION TO THE
OR
CONDITIONAL:You need to say:
The reason is that "or" splits up the condition into separate logical parts. The way your original statement was written, those parts were:
The last part was fine --- checking to see if z == 0, for instance --- but the first two parts just said essentially
if x
andif y
. Since integers always evaluate toTrue
unless they're 0, that means the first part of your condition was alwaysTrue
whenx
ory
didn't equal 0 (which in the case of y was always, since you hady = 1
, causing your whole condition (because of howOR
works) to always beTrue
.To avoid that, you need to make sure all parts of your condition (each side of the
OR
) make sense on their own (you can do that by pretending that the other side(s) of theOR
statement doesn't exist). That's how you can confirm whether or not yourOR
condition is correctly defined.You would write the statements individually like so:
which means the correct mergin with the
OR
keyword would be:SECOND, HOW TO SOLVE THE PROBLEM:
You're basically wanting to check to see if any of the variables match a given integer and if so, assign it a letter that matches it in a one-to-one mapping. You want to do that for a certain list of integers so that the output is a list of letters. You'd do that like this:
Similarly, you could use LIST COMPREHENSION to achieve the same result faster:
Set 是这里的好方法,因为它对变量进行排序,这似乎是您的目标。无论参数的顺序如何,
{z,y,x}
都是{0,1,3}
。这样,整个解决方案就是 O(n)。
Set is the good approach here, because it orders the variables, what seems to be your goal here.
{z,y,x}
is{0,1,3}
whatever the order of the parameters.This way, the whole solution is O(n).
我认为这会更好地处理它:
输出:
I think this will handle it better:
Output:
如果你想使用 if, else 语句,下面是另一种解决方案:
If you want to use if, else statements following is another solution:
这里提供的所有优秀答案都集中在原始发布者的具体要求上,并集中在 Martijn Pieters 提出的
if 1 in {x,y,z}
解决方案上。他们忽略的是问题的更广泛含义:
如何针对多个值测试一个变量?
如果使用字符串,则提供的解决方案不适用于部分命中:
测试字符串“Wild”是否处于多个值中
,或者
对于这种情况,最简单的方法是转换为字符串。
但是应该注意的是,正如
@codeforester
提到的,使用此方法会丢失单词边界,例如:3 个字母
rot
确实以组合形式存在于列表中,但不是作为单独的单词。测试“ rot ”将会失败,但如果列表项之一是“rot in hell”,那么也会失败。结果是,如果使用此方法,请小心您的搜索条件,并注意它确实有此限制。
All of the excellent answers provided here concentrate on the specific requirement of the original poster and concentrate on the
if 1 in {x,y,z}
solution put forward by Martijn Pieters.What they ignore is the broader implication of the question:
How do I test one variable against multiple values?
The solution provided will not work for partial hits if using strings for example:
Test if the string "Wild" is in multiple values
or
for this scenario it's easiest to convert to a string
It should be noted however, as mentioned by
@codeforester
, that word boundries are lost with this method, as in:the 3 letters
rot
do exist in combination in the list but not as an individual word. Testing for " rot " would fail but if one of the list items were "rot in hell", that would fail as well.The upshot being, be careful with your search criteria if using this method and be aware that it does have this limitation.
这段代码可能会有所帮助
This code may be helpful
您可以尝试下面所示的方法。在此方法中,您可以自由指定/输入您想要输入的变量数量。
You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.
您误解了布尔表达式的工作原理;它们不像英语句子那样工作,并且猜测您在这里谈论的是对所有名称的相同比较。您正在寻找:
x
和y
单独计算(False
if0
,否则为真
)。您可以使用针对 元组 的包含测试来缩短该时间:
或者更好的是:
使用 a
set
利用固定成本会员资格测试(即,无论左侧操作数是什么,in
都会花费固定的时间)。说明
当您使用
or
时,Python 将运算符的每一侧视为单独的 表达式。表达式x 或 y == 1
首先被视为对x
的布尔测试,然后如果为 False,则表达式y == 1
> 已测试。这是由于运算符优先级造成的。
or
运算符的优先级低于==
测试,因此后者首先被评估。然而,即使情况并非如此,并且表达式
x or y or z == 1
实际上被解释为(x or y or z) = = 1
相反,这仍然不会执行您期望的操作。x 或 y 或 z
将计算为第一个“true”参数,例如不是False
、数字 0 或空(请参阅 布尔表达式 了解有关 Python 在布尔上下文中认为 false 的详细信息)。因此对于值 x = 2; y = 1; z = 0、
x 或 y 或 z
将解析为2
,因为这是参数中第一个类似 true 的值。那么2 == 1
将为False
,即使y == 1
将为True
。这同样适用于相反的情况;针对单个变量测试多个值;由于同样的原因,
x == 1 or 2 or 3
也会失败。在 {1, 2, 3} 中使用x == 1 或 x == 2 或 x == 3
或x。
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:
x
andy
are otherwise evaluated on their own (False
if0
,True
otherwise).You can shorten that using a containment test against a tuple:
or better still:
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).Explanation
When you use
or
, python sees each side of the operator as separate expressions. The expressionx or y == 1
is treated as first a boolean test forx
, then if that is False, the expressiony == 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. notFalse
, 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 to2
, because that is the first true-like value in the arguments. Then2 == 1
would beFalse
, even thoughy == 1
would beTrue
.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. Usex == 1 or x == 2 or x == 3
orx in {1, 2, 3}
.使用字典结构可以更轻松地解决您的问题,例如:
Your problem is more easily addressed with a dictionary structure like:
正如 Martijn Pieters 所说,正确且最快的格式是:
使用他的建议,您现在将拥有单独的 if 语句,以便 Python 将读取每个语句,无论前者是
True
还是False
。例如:这会起作用,但是如果您习惯使用字典(看看我在那里做了什么),您可以通过创建一个将数字映射到您想要的字母的初始字典来清理它,然后只需使用 for 循环:
As stated by Martijn Pieters, the correct, and fastest, format is:
Using his advice you would now have separate if-statements so that Python will read each statement whether the former were
True
orFalse
. Such as:This will work, but if you are comfortable using dictionaries (see what I did there), you can clean this up by making an initial dictionary mapping the numbers to the letters you want, then just using a for-loop:
x or y or z == 0
的直接写法是But I don't think, you like it. :)
而且这种方式很丑陋。
另一种方式(更好)是:
顺便说一句,很多
if
可以写成这样The direct way to write
x or y or z == 0
isBut I dont think, you like it. :)
And this way is ugly.
The other way (a better) is:
BTW lots of
if
s could be written as something like this要检查某个值是否包含在一组变量中,您可以使用内置模块
itertools
和operator
。例如:
导入:
声明变量:
创建值映射(按照您要检查的顺序):
使用
itertools
允许重复变量:最后,使用
map
函数来创建迭代器:然后,在检查值时(按原始顺序),使用 next():
等等...
这比 lambda x: x 具有优势(变量)因为
operator
是一个内置模块,比使用必须创建自定义就地函数的lambda
更快、更高效。检查列表中是否存在非零(或 False)值的另一个选项:
等效:
To check if a value is contained within a set of variables you can use the inbuilt modules
itertools
andoperator
.For example:
Imports:
Declare variables:
Create mapping of values (in the order you want to check):
Use
itertools
to allow repetition of the variables:Finally, use the
map
function to create an iterator:Then, when checking for the values (in the original order), use
next()
:etc...
This has an advantage over the
lambda x: x in (variables)
becauseoperator
is an inbuilt module and is faster and more efficient than usinglambda
which has to create a custom in-place function.Another option for checking if there is a non-zero (or False) value in a list:
Equivalent:
如果你非常懒,你可以将值放入数组中。例如
您也可以将数字和字母放入字典中并执行此操作,但这可能比简单的 if 语句复杂得多。这就是你试图变得格外懒惰所得到的结果:)
还有一件事,你的
意志会编译,但不是以你想要的方式编译。当您简单地将变量放入 if 语句(示例)时,
程序将检查该变量是否不为空。编写上述语句的另一种方法(更有意义)是
Bool 是 python 中的内置函数,它基本上执行验证布尔语句的命令(如果你不知道那是什么,这就是你想要做的现在在你的 if 语句中:))
我发现的另一种懒惰方法是:
If you ARE very very lazy, you can put the values inside an array. Such as
You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)
One more thing, your
will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)
the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is
Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))
Another lazy way I found is :