我是 Python 新手,我碰巧注意到 5 in range(5,6) in [range(5,6)]
返回 True
。
有人可以向我解释这背后的逻辑是什么吗?这行不等于 True in [range(5,6)]
吗?为什么不?它到底是如何运作的?
谢谢:)
最佳答案
Python 允许您“链接”比较运算符 ( from the docs ):
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
和in
在上面的引用中算作比较运算符。所以该表达式相当于:
5 in range(5, 6) and range(5, 6) in [range(5, 6)]
这是True
,因为5
在该范围内,并且 range(5, 6)
就在该列表中。
关于python - 为什么 "5 in range(5,6) in [range(5,6)]"返回 True?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60169690/