x in range(...) == y 在 Python 3 中是什么意思? [英] What does x in range(...) == y mean in Python 3?

查看:67
本文介绍了x in range(...) == y 在 Python 3 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 Python 3 中偶然发现了以下行.

1 in range(2) == True

我期望这是 True,因为 1 in range(2) 为 True,True == True 为 True.

但这会输出False.所以它和 (1 in range(2)) == True 的意思不一样.此外,它与引发错误的 1 in (range(2) == True) 并不相同.

尽管有多年 Python 经验,我还是措手不及.这是怎么回事?

解决方案

这是因为两个运算符都是比较运算符,因此被解释为运算符链接:

https://docs.python.org/3.6/reference/expressions.html#comparisons

<块引用>

比较可以任意链接,例如,x <;y <= z 是等价的到 x ,除了 y 只计算一次(但在两个case zx <;y 被发现是假的).

所以等价于:

<预><代码>>>>(1 in range(2)) 和 (range(2) == True)错误的

I just stumbled upon the following line in Python 3.

1 in range(2) == True

I was expecting this to be True since 1 in range(2) is True and True == True is True.

But this outputs False. So it does not mean the same as (1 in range(2)) == True. Furthermore it does not mean the same as 1 in (range(2) == True) which raises an error.

Despite years of experience in Python, I am taken off guard. What is going on?

解决方案

This is due to the fact that both operators are comparison operators, so it is being interpreted as operator chaining:

https://docs.python.org/3.6/reference/expressions.html#comparisons

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 it is equivalent to:

>>> (1 in range(2)) and (range(2) == True)
False

这篇关于x in range(...) == y 在 Python 3 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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