首页 > 解决方案 > 在链接比较运算符python中分离表达式

问题描述

谁能解释一下,exp1 和 exp2 到底在做什么?请将每个案例分开,以便可以理解。

a, b, c, d, e, f = 0, 5, 12, 0, 15, 15

exp1 = a <= b < c > d is not e is f 
exp2 = a is d > f is not c 

print(exp1) 
print(exp2) 

标签: pythonpython-3.xcomparisonoperatorsboolean-expression

解决方案


exp1 = a <= b < c > d is not e is f被评估为a<=b and b<c and c>d and d is not e and e is f

两个表达式的字节码是相同的(dis 模块参考)。

In [8]: import dis

In [9]: dis.dis('a <= b < c > d is not e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               1 (<=)
             10 JUMP_IF_FALSE_OR_POP    48
             12 LOAD_NAME                2 (c)
             14 DUP_TOP
             16 ROT_THREE
             18 COMPARE_OP               0 (<)
             20 JUMP_IF_FALSE_OR_POP    48
             22 LOAD_NAME                3 (d)
             24 DUP_TOP
             26 ROT_THREE
             28 COMPARE_OP               4 (>)
             30 JUMP_IF_FALSE_OR_POP    48
             32 LOAD_NAME                4 (e)
             34 DUP_TOP
             36 ROT_THREE
             38 COMPARE_OP               9 (is not)
             40 JUMP_IF_FALSE_OR_POP    48
             42 LOAD_NAME                5 (f)
             44 COMPARE_OP               8 (is)
             46 RETURN_VALUE
        >>   48 ROT_TWO
             50 POP_TOP
             52 RETURN_VALUE

In [10]: dis.dis('a<=b and b<c and c>d and d is not e and e is f')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               1 (<=)
              6 JUMP_IF_FALSE_OR_POP    38
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
             14 JUMP_IF_FALSE_OR_POP    38
             16 LOAD_NAME                2 (c)
             18 LOAD_NAME                3 (d)
             20 COMPARE_OP               4 (>)
             22 JUMP_IF_FALSE_OR_POP    38
             24 LOAD_NAME                3 (d)
             26 LOAD_NAME                4 (e)
             28 COMPARE_OP               9 (is not)
             30 JUMP_IF_FALSE_OR_POP    38
             32 LOAD_NAME                4 (e)
             34 LOAD_NAME                5 (f)
             36 COMPARE_OP               8 (is)
        >>   38 RETURN_VALUE

exp2 = a is d > f is not c被评估为a is d and d>f and f is not c。它们都会产生相同的字节码。


推荐阅读