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 个回答
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 来了解优先级表。