包含非伸缩元素的集合的比较

2024-04-26 03:42:44 发布

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

在python中,值x并不总是约束为等于自身。最著名的例子是:

>>> x = float("NaN")
>>> x == x
False

现在考虑一个只有一个项目的列表。我们可以认为两个这样的列表是相等的,只要它们所包含的项目是相等的。例如:

>>> ["hello"] == ["hello"]
True

NaN的情况似乎并非如此:

>>> x = float("NaN")
>>> x == x
False
>>> [x] == [x]
True

所以这些“不相等”的项目列表是“相等”的。但只是有时候。。。特别是:

  • NaN的相同实例组成的两个列表被认为是相等的;而
  • NaN的不同实例组成的两个独立列表不相等

观察:

>>> x = float("NaN")
>>> [x] == [x]
True
>>> [x] == [float("NaN")]
False

这种一般行为也适用于其他集合类型,如元组和集合。这有一个很好的理由吗?你知道吗


Tags: 项目实例falsetrue类型hello列表情况
1条回答
网友
1楼 · 发布于 2024-04-26 03:42:44

根据the docs

In enforcing reflexivity of elements, the comparison of collections assumes that for a collection element x, x == x is always true. Based on that assumption, element identity is compared first, and element comparison is performed only for distinct elements. This approach yields the same result as a strict element comparison would, if the compared elements are reflexive. For non-reflexive elements, the result is different than for strict element comparison, and may be surprising: The non-reflexive not-a-number values for example result in the following comparison behavior when used in a list:

 >>> nan = float('NaN')
 >>> nan is nan
 True
 >>> nan == nan
 False                 <  the defined non-reflexive behavior of NaN
 >>> [nan] == [nan]
 True                  <  list enforces reflexivity and tests identity first

相关问题 更多 >