简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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