Python评估顺序

时间:2010-03-16 08:07:32

标签: python

这是代码,我不太明白,它是如何工作的。谁能告诉,这是预期的行为吗?

$ipython

In [1]: 1 in [1] == True
Out[1]: False

In [2]: (1 in [1]) == True
Out[2]: True

In [3]: 1 in ([1] == True)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/dmedvinsky/projects/condo/condo/<ipython console> in <module>()

TypeError: argument of type 'bool' is not iterable

In [4]: from sys import version_info

In [5]: version_info
Out[5]: (2, 6, 4, 'final', 0)

1 个答案:

答案 0 :(得分:15)

这是“链接”的一个例子,这是Python中的问题。这是Python的一个(可能是愚蠢的)技巧:

a op b op c

相当于:

(a op b) and (b op c)

对于具有相同优先级的所有运算符。不幸的是,in==具有相同的优先级,is和所有比较都具有相同的优先级。

所以,这是你的意外情况:

1 in [1] == True  # -> (1 in [1]) and ([1] == True) -> True and False -> False

有关优先顺序,请参见http://docs.python.org/reference/expressions.html#summary

相关问题