编程语言
首页 > 编程语言> > python – 对三个对象使用“==”运算符

python – 对三个对象使用“==”运算符

作者:互联网

这两种检查三个对象之间的相等性的方法之间是否有任何计算差异?

我有两个变量:x和y.说我这样做:

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

这有什么不同于:

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

如果它们是假的呢?

>>> 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,operators,equality
来源: https://codeday.me/bug/20191008/1870774.html