简体   繁体   English

无论给出阈值的顺序如何,我如何才能找到一个值是否介于两个特定阈值之间?

[英]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 = 3t2 = 5

a > t1 and a < t2 so the function func(a, t1, t2) returns true. a > t1a < 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 = 5t2 = 3 ,即使a = 4位于t1t2之间,该函数也会返回 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 <= t2t1 smallert2 larger ,否则t2 smallert1 larger

def func(a, t1, t2):
    smaller, larger = sorted([t1, t2])
    return smaller < a < larger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM