如何确定一个数字是否是任何类型的int(core或numpy,signed或not)?

2024-05-23 19:00:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

经过一些测试,我想:

  • isinstance(n, int)将只匹配intnp.int32(或np.int64,取决于平台形式)
  • np.issubdtype(type(n), int)似乎与所有intnp.int*匹配,但与np.uint*不匹配。

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

这是关于对整数的测试,对于float like,测试应该返回False


Tags: 类型typenp符号整数平台条件形式
2条回答

我建议将类型的元组传递给pythonisinstance()内置函数。关于您关于np.issubtype()的问题,它与任何类型的有符号int都不匹配,它确定一个类是否是第二个类的子类。而且由于所有整数类型(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

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,因为Pythonint是有符号类型。

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

enter image description here

相关问题 更多 >