在 Python 中一起使用 IF、AND、OR 和 EQUAL 操作数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38486621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using IF, AND, OR together with EQUAL operand together in Python
提问by jhub1
I'm trying to create a function where the given value (passed as a string) is checked to see if the number of digits is either 4 or 6, and that it is a number.
我正在尝试创建一个函数,在该函数中检查给定值(作为字符串传递)以查看位数是 4 还是 6,并且它是一个数字。
My first impulse was to go with this code:
我的第一个冲动是使用以下代码:
def number(x):
if (len(x) == (4 or 6)) and x.isdigit():
print "True"
else:
print "False"
This code above only passes the first test below...I don't understand why it passes this but none of the other tests:
上面的这段代码只通过了下面的第一个测试......我不明白为什么它通过了这个,但没有通过其他测试:
number("1234")
Only when I separate out the len() functions will it work properly.
只有当我分离出 len() 函数时,它才能正常工作。
def number(x):
if (len(x) == 4 or len(x) == 6) and x.isdigit():
print "True"
else:
print "False"
## Checks
number("1234")
number("123456")
number("abcd")
number("abcdef")
number("1")
number("a")
The above code passes all tests.
上面的代码通过了所有测试。
So my questions are:
所以我的问题是:
- What's going on here?
- Any way to write cleaner code for this?
- 这里发生了什么?
- 有没有办法为此编写更干净的代码?
Thank for the help!
感谢您的帮助!
** Not a duplicate question because although this question has the same underlying concepts regarding boolean operators, the problem itself is different due to the usage of len(), isdigit(), and the additional question of how best to improve it (someone commented the usage of return). Definitely adds another perspective to the other question though.
** 不是重复的问题,因为虽然这个问题在布尔运算符方面具有相同的基本概念,但由于使用了 len()、isdigit() 以及如何最好地改进它的附加问题(有人评论),问题本身是不同的返回的用法)。不过,绝对为另一个问题增加了另一个视角。
采纳答案by DavidO
It helps to examine the logic of this line:
它有助于检查这一行的逻辑:
if (len(x) == (4 or 6)):
The (4 or 6)
clause contains a logical or
short circuit. The value 4
is true, so it is evaluated and returned to the ==
relational comparison.
该(4 or 6)
子句包含逻辑or
短路。该值为4
真,因此对其进行评估并返回到==
关系比较。
The way that or
works is that its lefthand side is evaluated for Boolean truth, and its value is returned if true. If the lefthand side is not Boolean true, then the righthand side is evaluated and its value is returned.
其工作方式or
是评估其左侧是否为布尔真值,如果为真则返回其值。如果左侧不是布尔真,则评估右侧并返回其值。
Because the lefthand side of the 4 or ...
is true in a Boolean sense, the righthand side is never evaluated. Python doesn't even look past 4 or
. If the left-hand value were a false value (such as 0), then the right hand side of the or
would be evaluated.
由于 的左侧4 or ...
在布尔意义上为真,因此永远不会评估右侧。Python 甚至不看过去4 or
。如果左侧的值为假值(例如 0),则将or
评估的右侧。
To see this in action, try print 4 or 6
. The output will be 4.
要查看此操作,请尝试print 4 or 6
。输出将为 4。
So since the 4 is a hard-coded true value, your comparison is semantically the same as if (len(x) == 4)
-- that is, since 4 is true, 6 is never evaluated.
因此,由于 4 是硬编码的真值,因此您的比较在语义上与if (len(x) == 4)
- 也就是说,因为 4 为真,所以永远不会评估 6。
What I suppose you really want to know is if len(x)
is either 4 or 6. You could put that to code in a couple of ways:
我想您真正想知道的是len(x)
4 还是 6。您可以通过以下几种方式将其写入代码:
if(len(x) == 4 or len(x) == 6 ...
if(len(x) in (4,6) ...
回答by ifma
You can use the in
operator like so:
您可以in
像这样使用运算符:
def number(x):
if len(x) in (4, 6) and x.isdigit():
print "True"
else:
print "False"
where in
checks for containment in a given container. Note that 4 or 6
on their own evaluate to something undesirable, which is why your first code segment fails. You can check it out on the python shell:
wherein
检查给定容器中的容器。请注意,4 or 6
它们自己评估为不受欢迎的东西,这就是您的第一个代码段失败的原因。你可以在 python shell 上查看它:
>>> 4 or 6
4
回答by Charles Merriam
Short answer: len(x) in [4, 6]
or len(x) == 4 or len(x) == 6
.
简答:len(x) in [4, 6]
或len(x) == 4 or len(x) == 6
。
"or" is a boolean, or logical choice. (4 or 6) is guaranteed to resolve to a non-zero (true) value. In this case, it resolves to 4, so your test case passes.
“或”是一个布尔值或逻辑选择。(4 或 6) 保证解析为非零(真)值。在这种情况下,它解析为 4,因此您的测试用例通过。
回答by jonas_toth
You probably wanted to write
你可能想写
if (len(x) in (4, 6)) and x.isdigit():
Instead of
代替
if (len(x) == (4 or 6)) and x.isdigit():
回答by OneCricketeer
I'll go ahead and answer
我会继续回答
Any way to write cleaner code for this?
有没有办法为此编写更干净的代码?
Yes. Returnthe boolean value, rather than printing a string.
是的。返回布尔值,而不是打印字符串。
def number(x):
return len(x) in {4, 6} and x.isdigit()
print(number("1234")) # True
Then, it is simple do use your method in a if-statement without string comparison.
然后,在没有字符串比较的 if 语句中使用您的方法很简单。
回答by Ares
The trouble is in your or
statement.
问题出在你的or
陈述中。
Any value greater than one will evaluate to True
when you put it in a conditional. So (4 or 6)
will alwaysresolve to true.
任何大于 1 的值都将True
在您将其放入条件中时计算为。所以总是(4 or 6)
会下定决心为真。
You could use the in
statement above or you could just use two ==
's:
您可以使用in
上面的语句,也可以只使用两个==
:
if (len(x) == 4 or len(x) == 6) and x.isdigit()
if (len(x) == 4 or len(x) == 6) and x.isdigit()
It's a bit wordier, I find it easier to read.
它有点冗长,我觉得它更容易阅读。