为什么在numpy中,"nan == nan"是False而[nan]中的nan是True? [英] Why in numpy `nan == nan` is False while nan in [nan] is True?
问题描述
问题的第一部分(标题中)之前已经回答了几次(即如何检查包含NaN的列表)?
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)?
即:
>> nan == nan
False
>> nan in [nan]
True
考虑到@DSM的答案的问题解释性附录.那么,为什么float("nan")
的行为不同于nan
?它不应该再次对简单的nan
求值,为什么解释器会表现为这种方式?
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)
基本上,在第一种情况下它引用相同的泛型nan
,但是在第二种情况下创建单独的对象:
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
不等于nan
是nan
定义的一部分,因此很容易.
nan
not being equal to nan
is part of the definition of nan
, so that part's easy.
对于nan in [nan]
为True,这是因为在相等性之前对身份进行测试以包含在列表中.您正在比较相同的两个对象.
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.
如果您尝试使用两个不同 nan
进行相同的操作,则会得到False:
If you tried the same thing with two different nan
s, 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
您的附录与nan
并没有多大关系,这只是Python的工作方式.一旦您了解到float("nan")
没有义务返回某些nan单例,并且y = x
不会复制x
而是将名称y
绑定到由x
命名的对象,则一无所有.
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屋!