比较包含NaN的列表 [英] Comparing lists containing NaNs

查看:114
本文介绍了比较包含NaN的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较两个不同的列表以查看它们是否相等,并且打算删除NaN,只是发现尽管NaN == NaN -> False,我的列表比较仍然有效.

I am trying to compare two different lists to see if they are equal, and was going to remove NaNs, only to discover that my list comparisons still work, despite NaN == NaN -> False.

有人可以解释为什么以下内容评估TrueFalse,因为我发现此行为是意外的.谢谢,

Could someone explain why the following evaluate True or False, as I am finding this behavior unexpected. Thanks,

我已阅读以下内容,似乎无法解决该问题:

I have read the following which don't seem to resolve the issue:

  • Why in numpy nan == nan is False while nan in [nan] is True?
  • Why is NaN not equal to NaN? [duplicate]

(Python 2.7.3,numpy-1.9.2)

(Python 2.7.3, numpy-1.9.2)

我的评价令人吃惊,结尾处是*

I have marked surprising evaluations with a * at the end

>>> nan = np.nan
>>> [1,2,3]==[3]
False
>>> [1,2,3]==[1,2,3]
True
>>> [1,2,nan]==[1,2,nan]
True ***
>>> nan == nan
False
>>> [nan] == [nan]
True ***
>>> [nan, nan] == [nan for i in range(2)]
True ***
>>> [nan, nan] == [float(nan) for i in range(2)]
True ***
>>> float(nan) is (float(nan) + 1)
False
>>> float(nan) is float(nan)
True ***

推荐答案

要了解此处发生的情况,只需将nan = np.nan替换为foo = float('nan'),您将得到完全相同的结果,为什么?

To understand what happens here, simply replace nan = np.nan by foo = float('nan'), you will get exactly the same result, why?

>>> foo = float('nan')
>>> foo is foo # This is obviously True! 
True
>>> foo == foo # This is False per the standard (nan != nan).
False
>>> bar = float('nan') # foo and bar are two different objects.
>>> foo is bar
False
>>> foo is float(foo) # "Tricky", but float(x) is x if type(x) == float.
True

现在认为numpy.nan只是一个包含float('nan')的变量名.

Now think that numpy.nan is just a variable name that holds a float('nan').

现在为什么[nan] == [nan]仅仅是因为list比较首先要测试项目之间的身份相等性,然后才是价值相等,所以将其视为:

Now why [nan] == [nan] is simply because list comparison first test identity equality between items before equality for value, think of it as:

def equals(l1, l2):
    for u, v in zip(l1, l2):
        if u is not v and u != v:
            return False
    return True

这篇关于比较包含NaN的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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