[英]How can I find if a value lies between two specific thresholds regardless of the order in which the thresholds are given?
For example, if I have a value a = 4
and two input thresholds t1 = 3
and t2 = 5
.例如,如果我有一个值
a = 4
和两个输入阈值t1 = 3
和t2 = 5
。
a > t1
and a < t2
so the function func(a, t1, t2)
returns true. a > t1
和a < t2
所以函数func(a, t1, t2)
返回真。
But if I input t1 = 5
and t2 = 3
, even if a = 4
lies between the t1
and t2
, the function returns false.但是,如果我输入
t1 = 5
和t2 = 3
,即使a = 4
位于t1
和t2
之间,该函数也会返回 false。 How to solve this?如何解决这个问题?
So far I write this function in this way, but it only works when t1 < t2
.到目前为止,我以这种方式编写此函数,但它仅在
t1 < t2
时有效。 Is there some smart way to do this?有什么聪明的方法可以做到这一点吗?
def func(a, t1, t2):
if a > t1 and a < t2:
return True
else:
return False
You can use or
:您可以使用
or
:
def func(a, t1, t2):
return t1 < a < t2 or t2 < a < t1
print(func(4, 3, 5)) # True
print(func(4, 5, 3)) # True
print(func(4, 1, 2)) # False
Note that python allows chained comparisons so that you don't need to write t1 < a and a < t2
.请注意,python 允许链式比较,因此您无需编写
t1 < a and a < t2
。 Also, you don't need the redundant if
statement as in:此外,您不需要多余的
if
语句,如下所示:
if t1 < a < t2 or t2 < a < t1:
return True
else:
return False
You could order the two thresholds before using them in the comparison with a
, for example by using the sorted
function:您可以在与
a
进行比较之前对这两个阈值进行排序,例如使用sorted
函数:
smaller, larger = sorted([t1, t2])
If t1 <= t2
then smaller
will be t1
and larger
will be t2
, otherwise smaller
will be t2
and larger
will be t1
.如果
t1 <= t2
则t1
smaller
, t2
larger
,否则t2
smaller
, t1
larger
。
def func(a, t1, t2):
smaller, larger = sorted([t1, t2])
return smaller < a < larger
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.