为什么在 numpy `nan == nan` 中是 False 而 [nan] 中的 nan 是 True? [英] Why in numpy `nan == nan` is False while nan in [nan] is True?

查看:40
本文介绍了为什么在 numpy `nan == nan` 中是 False 而 [nan] 中的 nan 是 True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然问题的第一部分(在标题中)之前已经回答了几次(即,为什么 NaN 不等于 NaN?),我不明白为什么第二部分的工作方式如此(灵感来自这个问题 如何检查包含 NaN 的列表)?

即:

<代码>>>南==南错误的>>nan [nan]真的

<小时>

考虑到@DSM 的答案的问题的解释性附录.那么,为什么 float("nan")nan 的行为不同?难道它不应该再次评估为简单的 nan 以及解释器为什么会这样?

<代码>>>x = float("nan")>>y = 南>>X南>>是南>>x 是 nan,x 是 float("nan"),y 是 nan(假,假,真)

基本上,它在第一种情况下引用相同的泛型 nan,但在第二种情况下创建单独的对象:

<代码>>>nans = [nan for i in range(2)]>>地图(ID,南斯)[190459300、190459300]>>nans = [float("nan") for i in range(2)]>>地图(ID,南斯)[190459300、190459301]

解决方案

nan not equal to nannan 定义的一部分>,所以这部分很简单.

至于 nan in [nan] 为 True,那是因为在列表中包含的相等性之前测试身份.您正在比较相同的两个对象.

如果你用两个不同的 nans 尝试同样的事情,你会得到错误:

<预><代码>>>>nans = [float("nan") for i in range(2)]>>>地图(ID,南斯)[190459300、190459284]>>>南斯[楠,楠]>>>nans[0] 是 nans[1]错误的>>>nans[0] 在 nans真的>>>nans[0] 在 nans[1:]错误的

<小时>

您的附录与 nan 并没有多大关系,这只是 Python 的工作方式.一旦你明白 float("nan") 没有义务返回一些 nan 单例,并且 y = x 不会复制 x 而是将名称 y 绑定到由 x 命名的对象,没有什么可获取的了.

While the first part of the question (which is in the title) has been answered a few times before (i.e., Why is NaN not equal to NaN?), I don't see why the second piece works the way it does (inspired by this question How to Check list containing NaN)?

Namely:

>> nan == nan
False

>> nan in [nan]
True


An explanatory addendum to the question considering the answer from @DSM. So, why float("nan") is behaving differently from nan? Shouldn't it evaluate again to simple nan and why interpreter behaves this way?

>> x = float("nan")
>> y = nan
>> x
nan
>> y
nan
>> x is nan, x is float("nan"), y is nan
(False, False, True)

Basically, it refers to same generic nan in the first case, but creates separate object in the second:

>> nans = [nan for i in range(2)]
>> map(id, nans)
[190459300, 190459300]
>> nans = [float("nan") for i in range(2)]
>> map(id, nans)
[190459300, 190459301]

解决方案

nan not being equal to nan is part of the definition of nan, so that part's easy.

As for nan in [nan] being True, that's because identity is tested before equality for containment in lists. You're comparing the same two objects.

If you tried the same thing with two different nans, you'd get False:

>>> nans = [float("nan") for i in range(2)]
>>> map(id, nans)
[190459300, 190459284]
>>> nans
[nan, nan]
>>> nans[0] is nans[1]
False
>>> nans[0] in nans
True
>>> nans[0] in nans[1:]
False


Your addendum doesn't really have much to do with nan, that's simply how Python works. Once you understand that float("nan") is under no obligation to return some nan singleton, and that y = x doesn't make a copy of x but instead binds the name y to the object named by x, there's nothing left to get.

这篇关于为什么在 numpy `nan == nan` 中是 False 而 [nan] 中的 nan 是 True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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