gpt4 book ai didi

python - 运算符的优先级 : > and ==

转载 作者:IT老高 更新时间:2023-10-28 21:01:31 26 4
gpt4 key购买 nike

我试图猜测哪个运算符具有优先级:>(大于)或 ==(等于)。这是我的实验:

>>> 5 > 4 == 1
False

据我所知,这有两种可能的解决方案。

>>> (5 > 4) == 1
True
>>> 5 > (4 == 1)
True

都不返回False,那么Python是如何解析第一个代码的呢?

最佳答案

这与操作符链接有关。与 C/C++ 和大多数其他语言不同,Python 允许您像在普通数学中一样链接比较运算符。来自 documentation :

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).

所以,这个表达式:

5 > 4 == 1

实际上被解释为:

5 > 4 and 4 == 1  # Except that 4 is only evaluated once.

变成:

True and False

这是False .


然而,使用括号会改变 Python 解释您的比较的方式。这个:

(5 > 4) == 1

变成:

True == 1

这是True (原因见下文)。同样适用:

5 > (4 == 1)

变成:

5 > False

这也是 True .


因为PEP 0285 , bool成为 int 的子类和 True == 1False == 0 :

>>> issubclass(bool, int)
True
>>> True == 1
True
>>> False == 0
True
>>>

关于python - 运算符的优先级 : > and ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com