问题:简化链式比较

我有一个整数值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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。