【问题标题】:How to determine if a number is any type of int (core or numpy, signed or not)?如何确定一个数字是否是任何类型的 int(核心或 numpy,有符号或无符号)?
【发布时间】:2016-10-10 03:47:21
【问题描述】:

我需要测试变量是否为int 类型,或np.int*np.uint* 中的任何一个,最好使用单个条件(ie no or)。

经过一些测试,我猜是:

  • isinstance(n, int) 将仅匹配 intnp.int32(或 np.int64,具体取决于平台),
  • np.issubdtype(type(n), int) 似乎匹配所有 intnp.int*,但不匹配 np.uint*

这导致了两个问题:np.issubdtype 会匹配任何类型的有符号整数吗?可以在一次检查中确定一个数字是任何类型的有符号整数还是无符号整数?

这是关于 整数 的测试,该测试应返回 False 以获取 float-likes。

【问题讨论】:

  • 如果您想避免导入 NumPy,请考虑使用 isinstance(n, numbers.Integral)

标签: python numpy types


【解决方案1】:

NumPy 提供了可以/应该用于子类型检查的基类,而不是 Python 类型。

使用np.integer 检查有符号或无符号整数的任何实例。

使用np.signedintegernp.unsignedinteger 检查有符号类型或无符号类型。

>>> np.issubdtype(np.uint32, np.integer)
True
>>> np.issubdtype(np.uint32, np.signedinteger)
False
>>> np.issubdtype(int, np.integer)
True

所有浮点数或复数类型在测试时都将返回False

np.issubdtype(np.uint*, int) 将始终为 False,因为 Python int 是有符号类型。

在文档here 中可以找到显示所有这些基类之间关系的有用参考。

【讨论】:

  • 我肯定投了赞成票,这允许使用:isinstance(n, (int, np.integer)) 进行测试。
  • @ArcturusB:我对你的评论感到困惑,因为我对这两个陈述都得到了 False:isinstance(np.array(1, dtype=np.int32), np.int32)isinstance(np.array(1, dtype=np.int32), np.integer)
  • @ArcturusB,您正在针对整数类型测试数组,因此您得到 False 结果。试试isinstance(np.int32(1), np.int32)
  • 我觉得奇怪的是np.issubdtype( int, np.integer ) 是 True:int 可以只要适合内存,np.integer( sys.maxsize ** 2 ) 引发 OverflowError: Python int too large to convert to C long.
【解决方案2】:

我建议将类型元组传递给 python isinstance() 内置函数。关于您关于np.issubtype() 的问题,它与任何类型的签名整数都不匹配,它确定一个类是否是第二类的子类。由于所有整数类型(int8、int32 等)都是 int 的子类,如果您将其中任何一个类型与 int 一起传递,它将返回 True。

这是一个例子:

>>> a = np.array([100])
>>> 
>>> np.issubdtype(type(a[0]), int)
True
>>> isinstance(a[0], (int, np.uint))
True
>>> b = np.array([100], dtype=uint64)
>>> 
>>> isinstance(b[0], (int, np.uint))
True

另外,作为一种更通用的方法(当您只想匹配某些特定类型时不合适)您可以使用np.isreal()

>>> np.isreal(a[0])
True
>>> np.isreal(b[0])
True
>>> np.isreal(2.4) # This might not be the result you want
True
>>> np.isreal(2.4j)
False

【讨论】:

  • 感谢您对np.issutype() 的澄清。我猜想在isinstance() 中列出类型会起作用,但我想避免这种情况,因为这意味着要执行isinstance(n, (int, np.int, np.int0, np.int8, np.int16, <etc.>, np.uint, <etc.>)。我想不出比 Pythonic 更少的了。
  • @ArcturusB 在这种情况下,您可能希望使用更通用的类型和整数的父类型。看看 numpy 数据输入docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html
  • 确实,按照 ajcr 的建议使用 np.integer 可以正常工作;谢谢!
猜你喜欢
  • 2010-12-06
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 2014-06-21
  • 2011-04-18
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
相关资源
最近更新 更多