比较python中的两个布尔表达式

2024-05-02 04:57:04 发布

您现在位置:Python中文网/ 问答频道 /正文

In[19]: x = None
In[20]: y = "Something"
In[21]: x is None == y is None
Out[21]: False
In[22]: x is None != y is None ## What's going on here?
Out[22]: False
In[23]: id(x is None)
Out[23]: 505509720
In[24]: id(y is None)
Out[24]: 505509708

为什么Out[22]是假的?他们有不同的身份证,所以这不是身份问题。。。。你知道吗


Tags: innoneidfalsehereison身份
2条回答

你的x is None != y is None是“chained comparisons”。更典型的例子是3 < x < 9。意思与(3 < x) and (x < 9)相同。在你的例子中,使用操作符is!=,这是:

(x is None) and (None != y) and (y is None)

这是假的,因为y is None是假的。你知道吗

链式表达式从左到右求值,此外,比较is!=具有相同的优先级,因此表达式的求值方式为:

(x is None) and (None!= y) and (y is None)
# -True  |   True  -| - False -|
#     -True      |
#         False        -|

要更改评估顺序,您应该放置一些参数:

>>> (x is None) != (y is None)
True

还要注意的是,第一个表达式x is None == y is None是一个侥幸心理,或者更确切地说是一个危险因素,因为如果在所需的位置放置一些paren,您将得到相同的结果。这可能就是为什么您假设顺序应该首先从is开始,然后在第二种情况下从!=开始。你知道吗

相关问题 更多 >