为什么布尔表达式"1 in(1,2,3)== True"为假?

Int*_*rit 5 python boolean-logic operator-precedence

为什么语句在Python中1 in (1, 2, 3) == True返回False?Python中的运算符优先级是不明确的吗?

jon*_*rpe 10

因为,根据运算符优先级的文档:

请注意,比较,成员资格测试和身份测试都具有相同的优先级,并具有从" 比较"部分中所述的从左到右的链接功能.

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

比较可以任意链接,例如,x < y <= z相当于x < y and y <= z

所以:

1 in (1, 2, 3) == True
Run Code Online (Sandbox Code Playgroud)

被解释为:

(1 in (1, 2, 3)) and ((1, 2, 3) == True)
Run Code Online (Sandbox Code Playgroud)

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

>>> (1 in (1, 2, 3)) == True
True
Run Code Online (Sandbox Code Playgroud)

请注意,不要将相等的真实性与True或者比较,而False应该使用eg if thing:if not thing:.


归档时间:

查看次数:

513 次

最近记录:

9 年,9 月 前