我如何确定一个给定的整数是否在另外两个整数之间(例如大于/等于10000和小于/等于30000)?

到目前为止,我的尝试并没有奏效:

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

当前回答

虽然10 <= number <= 20适用于Python,但我发现使用range()的表示法更具可读性:

if number in range(10, 21):
    print("number is between 10 (inclusive) and 21 (exclusive)")
else:
    print("outside of range!")

请记住,第二个上限参数不包括在范围设置中,可以通过以下方法验证:

>>> list(range(10, 21))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

但是,只有当range()方法没有运行在某些性能关键路径上时才使用它。对于大多数需求来说,单个调用仍然足够快,但如果运行10,000,000次,我们清楚地注意到与A <= x < b相比,性能要慢近3倍:

> { time python3 -c "for i in range(10000000): x = 50 in range(1, 100)"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
1.848

> { time python3 -c "for i in range(10000000): x = 1 <= 50 < 100"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
0.630

其他回答

有两种方法比较三个整数并检查b是否在a和c之间:

if a < b < c:
    pass

and

if a < b and b < c:
    pass

第一个看起来可读性更好,但第二个运行得更快。

让我们使用dis.dis进行比较:

>>> dis.dis('a < b and b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               0 (<)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
        >>   14 RETURN_VALUE
>>> dis.dis('a < b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               0 (<)
             10 JUMP_IF_FALSE_OR_POP    18
             12 LOAD_NAME                2 (c)
             14 COMPARE_OP               0 (<)
             16 RETURN_VALUE
        >>   18 ROT_TWO
             20 POP_TOP
             22 RETURN_VALUE
>>>

使用timeit:

~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop

此外,您也可以使用range,正如之前建议的那样,但是它要慢得多。

>>> r = range(1, 4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False

我添加了一个没有人提到的解决方案,使用symphony库中的Interval类:

from sympy import Interval

lower_value, higher_value = 10000, 30000
number = 20000

 # to decide whether your interval shhould be open or closed use left_open and right_open 
interval = Interval(lower_value, higher_value, left_open=False, right_open=False)
if interval.contains(number):
    print("you have to pay 5% taxes")

下面是一些可能的方法,从最好到最差的表现(即第一个将表现最好)

     # Old school check
     if 10000 >= b and b <=30000:
        print ("you have to pay 5% taxes")
     # Python range check
     if 10000 <= number <= 30000:
        print ("you have to pay 5% taxes")
     # As suggested by others but only works for integers and is slow
     if number in range(10000,30001):
        print ("you have to pay 5% taxes")
if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")