【问题标题】:Why does np.float('nan') cause problems with dicts, but math.nan does not?为什么 np.float('nan') 会导致 dicts 出现问题,但 math.nan 不会?
【发布时间】:2019-10-31 20:45:42
【问题描述】:

正如this question 中显示的那样,从 numpy 中使用 nan 如何导致 dict 出现问题,为什么 math.nan 的行为会有所不同? (Python3)

import math
import numpy as np

d = {math.nan:'baz', math.nan:'bip' }
print(d)
e = {np.float('nan'):'foo', np.float('nan'):'bar' }
print(e)

输出

{nan: 'bip'}
{nan: 'foo', nan: 'bar'}

【问题讨论】:

  • 此外,以下两个都是真的:math.nan is math.nannp.float('nan') is not np.float('nan')
  • 事实上,在很多平台上,np.float is float
  • @wim:在numpy 是官方发行版的每个平台上

标签: python numpy


【解决方案1】:

这是因为math.nan 是模块级别的属性,所以两次都得到相同的对象。 CPython dicts 有一个快捷方式 用于身份检查

>>> any(k == math.nan for k in d)
False
>>> math.nan in d
True

使用np.float('nan') 你有一个函数调用,每次都返回不同的实例。使用 Python 内置的 float('nan') 会再次类似,这与 numpy 并没有真正的关系。

>>> np.float('nan') is np.float('nan')
False
>>> math.nan is math.nan
True
>>> float('nan') is float('nan')
False

列表、元组等也有这个。有关更多信息,请参阅Making an object x such that “x in [x]” returns False

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2019-11-15
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多