"=="的用法三个对象的运算符 [英] Usage of the "==" operator for three objects

查看:96
本文介绍了"=="的用法三个对象的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种检查三个对象之间相等性的方法之间在计算上有区别吗?

Is there any computational difference between these two methods of checking equality between three objects?

我有两个变量:xy.说我这样做:

I have two variables: x and y. Say I do this:

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

它们的计算方式是否有差异?

Is there any difference in how they are calculated?

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

提前谢谢!

推荐答案

Python具有链式比较,因此这两种形式是等效的:

Python has chained comparisons, so these two forms are equivalent:

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

除了在第一个中,y仅被评估一次.

except that in the first, y is only evaluated once.

这意味着您还可以编写:

This means you can also write:

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

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

etc. You can also write confusing things like:

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

初学者有时会被绊倒:

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

由于与以下内容相同,因此始终为假:

which will always be false since it is the same as:

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

这篇关于"=="的用法三个对象的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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