>> x == x False 现在考虑一个只有一个项目的列表。当且仅-6ren">
gpt4 book ai didi

python - 比较包含非自反元素的集合

转载 作者:太空狗 更新时间:2023-10-29 20:23:52 25 4
gpt4 key购买 nike

在 python 中,值 x 并不总是被限制为等于自身。也许最著名的例子是 NaN:

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

这种一般行为也适用于其他集合类型,例如元组和集合。这有充分的理由吗?

最佳答案

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

关于python - 比较包含非自反元素的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com