简体   繁体   English

如何检查某个数字是否在某个区间内

[英]How to check if a number is in a interval

Suppose I got: 假设我得到了:

first_var = 1
second_var = 5
interval = 2

I want an interval from second_var like second_var ± interval (from 3 to 7). 我想要second_var的间隔,如second_var ± interval (从3到7)。 I wank to check if first_var is in that interval. 我想知道first_var是否在那段时间内。 So in this specific case I want False If first_var = 4 , I want True 所以在这种特殊情况下我想要False如果first_var = 4 ,我想要True

I can do this: 我可以做这个:

if (first_var > second_var-interval) and (first_var < second_var+interval):
  #True

Is there a more pythonic way to do this? 是否有更多的pythonic方式来做到这一点?

You can use math-like sequence as Python supports that 您可以使用类似数学的序列,因为Python支持它

if (second_var-interval < first_var < second_var+interval):
     # True

Note that comments in python begin with a # 请注意,python中的注释以#开头

I use a class with __contains__ to represent the interval: 我使用带__contains__的类来表示间隔:

class Interval(object):
    def __init__(self, middle, deviation):
        self.lower = middle - abs(deviation)
        self.upper = middle + abs(deviation)

    def __contains__(self, item):
        return self.lower <= item <= self.upper

Then I define a function interval to simplify the syntax: 然后我定义一个函数interval来简化语法:

def interval(middle, deviation):
    return Interval(middle, deviation)

Then we can call it as follows: 然后我们可以这样称呼它:

>>> 8 in interval(middle=6, deviation=2)
True

>>> 8 in interval(middle=6, deviation=1)
False

With Python 2 this solution is more efficient than using range or xrange as they don't implement __contains__ and they have to search for a matching value. 使用Python 2,这个解决方案比使用rangexrange更有效,因为它们没有实现__contains__并且它们必须搜索匹配的值。

Python 3 is smarter and range is a generating object which is efficient like xrange , but also implements __contains__ so it doesn't have to search for a valid value. Python 3更智能, range是一个生成对象,它像xrange一样高效,但也实现__contains__因此它不必搜索有效值。 xrange doesn't exist in Python 3. Python 3中不存在xrange

This solution also works with floats. 此解决方案也适用于浮动。

Also, note, if you use range you need to be careful of off-by-1 errors. 另外,请注意,如果使用range ,则需要注意1分之一的错误。 Better to encapsulate it, if you're going to be doing it more than once or twice. 最好将其封装起来,如果你要做的不止一次或两次。

You can use lambdas: 你可以使用lambdas:

lmd = lambda fv, sv, inval: print('True') if \
    sv - inval < fv < sv + inval else print('False')

and use it like: 并使用它像:

lmd(first_var, second_var, interval)

but it's a little bit long! 但它有点长!

if (first_var in range(second_var-interval, second_var+interval+1)):
    #Do something

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

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