gpt4 book ai didi

python - 对三个对象使用 "=="运算符

转载 作者:太空狗 更新时间:2023-10-29 22:11:38 24 4
gpt4 key购买 nike

这两种检查三个对象是否相等的方法在计算上有什么不同吗?

我有两个变量:xy。假设我这样做:

>>> x = 5
>>> y = 5
>>> x == y == 5
True

这有什么不同吗:

>>> x = 5
>>> y = 5
>>> x == y and x == 5
True

如果它们是 False 怎么办?

>>> x = 5
>>> y = 5
>>> x == y == 4
False

和:

>>> x = 5
>>> y = 5
>>> x == y and x == 4
False

它们的计算方式有什么不同吗?

此外,x == y == z 是如何工作的?

提前致谢!

最佳答案

Python 有链式比较,所以这两种形式是等价的:

x == y == z
x == y and y == z

除了在第一个中,y 只计算一次。

这意味着你还可以这样写:

0 < x < 10
10 >= z >= 2

等您还可以编写令人困惑的内容,例如:

a < b == c is d   # Don't  do this

初学者有时会被这个绊倒:

a < 100 is True   # Definitely don't do this!

这将永远是错误的,因为它与:

a < 100 and 100 is True   # Now we see the violence inherent in the system!

关于python - 对三个对象使用 "=="运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13792604/

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