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

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

if number >= 10000 and number >= 30000:
    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")

其他回答

有两种方法比较三个整数并检查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,正如之前建议的那样,但是它要慢得多。

试试这个简单的函数;它检查A是否在B和C之间(B和C的顺序可能不对):

def isBetween(A, B, C):
    Mi = min(B, C)
    Ma = max(B, C)
    return Mi <= A <= Ma

所以isBetween(2, 10, -1)和isBetween(2, -1, 10)是一样的。

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

     # 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")

我添加了一个没有人提到的解决方案,使用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")
if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")