1
根據python文檔,x<y<z
比較被翻譯爲x<y and y<z
,並且表達式y
最多隻評估一次。
現在我的問題是,表達式y
(看下面的代碼)在這裏只評估一次嗎?Python比較評估
if(x<y and y<z):
根據python文檔,x<y<z
比較被翻譯爲x<y and y<z
,並且表達式y
最多隻評估一次。
現在我的問題是,表達式y
(看下面的代碼)在這裏只評估一次嗎?Python比較評估
if(x<y and y<z):
兩次:
>>> 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
>>>
號:
>>> 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
是什麼讓你認爲Python將優化呢?你有報價或參考指出它優化? – 2010-02-09 18:14:28
難道你不能...試試看,找出來? – 2010-02-10 01:56:11