奇数运算符优先级/关联行为 [英] Odd operator precedence/associativity behaviour

查看:108
本文介绍了奇数运算符优先级/关联行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2.7中,以下内容如何

How is it that, in Python 2.7, the following

True == 'w' in 'what!?'

行为不同于两者

(True == 'w') in 'what!?'

True == ('w' in 'what!?')

?

>>> True == 'w' in 'what!?'
False

>>> (True == 'w') in 'what!?'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not bool

>>> True == ('w' in 'what!?')
True

推荐答案

在Python中,比较可以为链接在一起:

In Python, comparisons can be chained together:

比较可以任意链接,例如x

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

所以您的代码实际上等效于

So your code is actually equivalent to

>>> (True == 'w') and ('w' in 'what!?')
False

这篇关于奇数运算符优先级/关联行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆