间隔比较如何工作? [英] How does interval comparison work?

查看:62
本文介绍了间隔比较如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以某种方式起作用,

def in_range(min, test, max):
    return min <= test <= max

print in_range(0, 5, 10)  # True
print in_range(0, 15, 10)  # False

但是,我不太清楚这里的操作顺序。让我们测试 False 的情况:

However, I can't quite figure out the order of operations here. Let's test the False case:

print 0 <= 15 <= 10  # False
print (0 <= 15) <= 10  # True
print 0 <= (15 <= 10)  # True

很显然,这并不能解决简单的操作顺序问题。区间比较是一个特殊的运算符,还是其他的事情?

Clearly, this isn't resolving to a simple order of operations issue. Is the interval comparison a special operator, or is something else going on?

推荐答案

与大多数语言不同,Python支持链式比较运算符,并且可以像在普通数学中对它们进行评估那样对其进行评估。

Unlike most languages, Python supports chained comparison operators and it evaluates them as they would be evaluated in normal mathematics.

此行:

return min <= test <= max

由Python评估如下:

is evaluated by Python like this:

return (min <= test) and (test <= max)

大多数其他语言都会这样评价它:

Most other languages however would evaluate it like this:

return (min <= test) <= max

这篇关于间隔比较如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆