How to find whether a number belongs to a particular range in Python? [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 14:18:12

问题


Suppose I want to check if x belongs to range 0 to 0.5. How can I do it?


回答1:


No, you can't do that. range() expects integer arguments. If you want to know if x is inside this range try some form of this:

print 0.0 <= x <= 0.5

Be careful with your upper limit. If you use range() it is excluded (range(0, 5) does not include 5!)




回答2:


print 'yes' if 0 < x < 0.5 else 'no'

range() is for generating arrays of consecutive integers




回答3:


>>> s = 1.1
>>> 0<= s <=0.2
False
>>> 0<= s <=1.2
True



回答4:


if num in range(min, max):
  """do stuff..."""
else:
  """do other stuff..."""



回答5:


To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.




回答6:


I would use the numpy library, which would allow you to do this for a list of numbers as well:

from numpy import array
a = array([1, 2, 3, 4, 5, 6,])
a[a < 2]



回答7:


Old faithful:

if n >= a and n <= b:

And it doesn't look like Perl (joke)



来源:https://stackoverflow.com/questions/618093/how-to-find-whether-a-number-belongs-to-a-particular-range-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!