简化链式比较

问题:简化链式比较

我有一个整数值x,我需要检查它是否在startend值之间,因此我编写了以下语句:

if x >= start and x <= end:
    # do stuff

该声明带有下划线,并且工具提示告诉我必须

简化链式比较

据我所知,这种比较就和它们来的一样简单。我在这里错过了什么?

I have an integer value x, and I need to check if it is between a start and end values, so I write the following statements:

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?


回答 0

在Python中,您可以“链接”比较操作,这仅意味着它们“并”在一起。在您的情况下,将是这样的:

if start <= x <= end:

参考:https : //docs.python.org/3/reference/expressions.html#comparisons

In Python you can “chain” comparison operations which just means they are “and”ed together. In your case, it’d be like this:

if start <= x <= end:

Reference: https://docs.python.org/3/reference/expressions.html#comparisons


回答 1

可以重写为:

start <= x <= end:

要么:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....

It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....

回答 2

简化代码

if start <= x <= end: # start x is between start and end 
# do stuff

Simplification of the code

if start <= x <= end: # start x is between start and end 
# do stuff