根据python文档,x<y<z
比较转换为x<y and y<z
,表达式y
最多只评估一次。
现在我的问题是,表达式y
(看下面的代码)在这里只评估一次吗?
if(x<y and y<z):
答案 0 :(得分:9)
两次:
>>> def f():
... print "F called"
... return 1
...
>>> 0 < f() < 100
F called
True
>>> 0 < f() and f() < 100
F called
F called
True
>>> if (0 < f() and f() < 100):
... print True
...
F called
F called
True
>>>
答案 1 :(得分:3)
没有
>>> dis.dis(lambda x, y, z: x < y() < z)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 CALL_FUNCTION 0
9 DUP_TOP
10 ROT_THREE
11 COMPARE_OP 0 (<)
14 JUMP_IF_FALSE 8 (to 25)
17 POP_TOP
18 LOAD_FAST 2 (z)
21 COMPARE_OP 0 (<)
24 RETURN_VALUE
>> 25 ROT_TWO
26 POP_TOP
27 RETURN_VALUE
>>> dis.dis(lambda x, y, z: x < y() and y() < z)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 CALL_FUNCTION 0
9 COMPARE_OP 0 (<)
12 JUMP_IF_FALSE 13 (to 28)
15 POP_TOP
16 LOAD_FAST 1 (y)
19 CALL_FUNCTION 0
22 LOAD_FAST 2 (z)
25 COMPARE_OP 0 (<)
>> 28 RETURN_VALUE