比较包含NaN的列表

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

有人可以解释为什么以下评估为TrueFalse ,因为我发现这种行为出乎意料。 谢谢,

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

  • 为什么在numpy nan == nan是false而nan在nan是真的?
  • 为什么NaN不等于NaN? [重复]
  • (Python 2.7.3,numpy-1.9.2)

    最后我用*标出了惊人的评价

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

    为了理解这里发生了什么,只需用foo = float('nan')替换nan = np.nan ,就会得到完全相同的结果,为什么?

    >>> 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')的变量名。

    现在为什么[nan] == [nan]仅仅是因为list比较首先在等价值之前测试项目之间的标识符相等性,可以认为它是:

    def equals(l1, l2):
        for u, v in zip(l1, l2):
            if u is not v and u != v:
                return False
        return True
    
    链接地址: http://www.djcxy.com/p/73353.html

    上一篇: Comparing lists containing NaNs

    下一篇: Python: sort function breaks in the presence of nan