2013-03-14 49 views
10

有人向我展示了python語法這個奇怪的例子。爲什麼[4]工作?這個python語法怎麼回事? (c == cs)

我本來會期望它評估爲[5]或[6],兩者都不起作用。有沒有一些過早的優化在這裏不應該是?

In [1]: s = 'abcd' 

In [2]: c = 'b' 

In [3]: c in s 
Out[3]: True 

In [4]: c == c in s 
Out[4]: True 

In [5]: True in s 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-5-e00149345694> in <module>() 
----> 1 True in s 

TypeError: 'in <string>' requires string as left operand, not bool 

In [6]: c == True 
Out[6]: False 

回答

13

這是相同的語法糖,允許蟒到鏈中的多個運算符(如<)在一起。

例如:

>>> 0 < 1 < 2 
True 

這相當於(0<1) and (1<2),不同之處在於中間表達式僅被評估一次。

陳述c == c in s類似地等同於(c == c) and (c in s),其評估爲True

爲了突出較早點,中間表達式僅被評估一次:

>>> def foo(x): 
...  print "Called foo(%d)" % x 
...  return x 
... 
>>> print 0 < foo(1) < 2 
Called foo(1) 
True 

更多細節參見Python Language Reference