[英]Check if value is between pair of values in a tuple?
Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple? 是否有一种有效的方法(很好的语法)来检查值是否在元组中包含的两个值之间?
The best thing I could come up with is: 我能想到的最好的事情是:
t = (1, 2)
val = 1.5
if t[0] <= val <= t[1]:
# do something
Is there a nicer way to write the conditional? 是否有更好的方法来编写条件?
No, there is no dedicated syntax, using chained comparisons is the right way to do this already. 不,没有专门的语法,使用链式比较是正确的方法。
The one 'nicety' I can offer is to use tuple unpacking first, but that's just readability icing here: 我能提供的“精确”是首先使用元组解包,但这只是可读性结冰:
low, high = t
if low <= val <= high:
If you are using a tuple subclass produced by collection.namedtuple()
you could of course also use the attributes here: 如果您正在使用collection.namedtuple()
生成的元组子类,您当然也可以使用以下属性:
from collections import namedtuple
range_tuple = namedtuple('range_tuple', 'low high')
t = range_tuple(1, 2)
if t.low <= val <= t.high:
You could make your own sugar: 你可以制作自己的糖:
class MyTuple(tuple):
def between(self, other):
# returns True if other is between the values of tuple
# regardless of order
return min(self) < other < max(self)
# or if you want False for MyTuple([2,1]).between(1.5)
# return self[0] < other < self[1]
mt=MyTuple([1,2])
print mt.between(1.5)
# True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.