Python 简化链式比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26502775/
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
Simplify Chained Comparison
提问by Brynn McCullagh
I have an integer value x, and I need to check if it is between a startand endvalues, so I write the following statements:
我有一个整数 value x,我需要检查它是否在 astart和endvalues之间,所以我写了以下语句:
if x >= start and x <= end:
# do stuff
This statement gets underlined, and the tooltip tells me that I must
该语句带有下划线,工具提示告诉我必须
simplify chained comparison
简化链式比较
As far as I can tell, that comparison is about as simple as they come. What have I missed here?
据我所知,这种比较和它们来的一样简单。我在这里错过了什么?
采纳答案by John Zwinck
In Python you can "chain" comparison operationswhich just means they are "and"ed together. In your case, it'd be like this:
在 Python 中,您可以“链接”比较操作,这意味着它们被“和”在一起。在你的情况下,它会是这样的:
if start <= x <= end:
Reference: https://docs.python.org/3/reference/expressions.html#comparisons
参考:https: //docs.python.org/3/reference/expressions.html#comparisons
回答by Maroun
It can be rewritten as:
可以改写为:
start <= x <= end:
Or:
或者:
r = range(start, end + 1) # (!) if integers
if x in r:
....
回答by Thomson Lukose
Simplification of the code
代码的简化
if start <= x <= end: # start x is between start and end
# do stuff

