判断相同的对象,bool函数在python中给出了两个不同的结果

To judge identical objects, bool function gives two different results in python

我需要创建一个列表,其中包含 10 个不同的 Python 对象,这些对象都是虚假的。每当 ab 是列表中不同位置的条目时,列表必须具有 a is b 计算结果为 False 的 属性。我找到了一个,但有两个条目让我感到困惑:0<0False。 我写了一些代码来测试这两个对象是否相同。

 bool(0>0 is False)

结果是False

但是当我运行代码:

mylist=[0>0,False]
bool(mylist[0] is mylist[1])

它returns True.

那么Python中的两个对象是否相同?

您需要添加括号...

bool(0>0 is False)

False因为步骤是先计算0 is False然后检查是否0 > (0 is False).python”链" 逻辑子句。
例如,考虑一个更熟悉的链接案例:

4 > 2 > 9

相当于

(4 > 2) and (2 > 9)  # => True and False => False

所以在你的案例中发生的链接等同于

(0 > 0) and (0 is False)  # => False and False (+ syntax-warning) => False

当然是 False

如果您尝试以下操作 -

bool((0 > 0) is False)

你得到了所需的True


由于评论和@buran 的回答,编辑后实际上是正确的。 感谢更正,原回答有误导,敬请见谅。

你的第一行被认为是

0 > (0 is False)

这样说就可以了:

(0 > 0) is False   # ==> True

Looking at the docs,看注释:

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

粗体是我的。

基本上,您的表达式 0>0 is False 等同于 (0>0) and (0 is False),即 False and False,所以 bool(False) -> False

其他回答中提到,加括号即可解决问题(0 > 0) is False