为什么布尔表达式“(1,2,3)中的1 == True"?错误的? [英] Why is the boolean expression "1 in (1, 2, 3) == True" False?

查看:212
本文介绍了为什么布尔表达式“(1,2,3)中的1 == True"?错误的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么语句1 in (1, 2, 3) == True在Python中返回False? Python中的运算符优先级是否模棱两可?

Why does the statement 1 in (1, 2, 3) == True return False in Python? Is the operator priority in Python ambiguous?

推荐答案

因为,根据

请注意,比较,成员资格测试和身份测试均具有 具有相同的优先级,并具有从左到右的链接功能 在比较部分中进行了说明.

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

比较"部分显示了链接的示例:

The Comparisons section shows an example of the chaining:

比较可以任意链接,例如x < y <= z是等效的 到x < y and y <= z

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z

所以:

1 in (1, 2, 3) == True

被解释为:

(1 in (1, 2, 3)) and ((1, 2, 3) == True)

如果通过添加括号覆盖此链接,则会获得预期的行为:

If you override this chaining by adding parentheses, you get the expected behaviour:

>>> (1 in (1, 2, 3)) == True
True

请注意,您不必使用相等性将真实性与TrueFalse进行比较,而应使用例如if thing:if not thing:.

Note that, rather than comparing truthiness by equality to True or False, you should just use e.g. if thing: and if not thing:.

这篇关于为什么布尔表达式“(1,2,3)中的1 == True"?错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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