问题描述
我需要测试变量是否为类型int
或np.int*
,np.uint*
中的任何一个,最好使用单个条件( ie 否or
).
I need to test whether a variable is of type int
, or any of np.int*
, np.uint*
, preferably using a single condition (i.e. no or
).
经过一些测试,我想:
-
isinstance(n, int)
仅匹配int
和np.int32
(或np.int64
取决于平台), -
np.issubdtype(type(n), int)
似乎与所有int
和np.int*
都匹配,但与np.uint*
不匹配.
isinstance(n, int)
will only matchint
andnp.int32
(ornp.int64
depending on plateform),np.issubdtype(type(n), int)
seems to match allint
andnp.int*
, but doesn’t matchnp.uint*
.
这导致两个问题:np.issubdtype
是否会匹配任何种带符号的整数?可以一次检查数字是否为带符号的整数或无符号的整数吗?
This leads to two questions: will np.issubdtype
match any kind of signed ints? Can determine in a single check whether a number is any kind of signed or unsigned int?
这是关于测试 integers 的,测试应返回False
浮点型.
This is about testing for integers, the test should return False
for float-likes.
推荐答案
NumPy提供了您可以/应该用于子类型检查的基类,而不是Python类型.
NumPy provides base classes that you can/should use for subtype-checking, rather than the Python types.
使用np.integer
检查有符号整数或无符号整数的任何实例.
Use np.integer
to check for any instance of either signed or unsigned integers.
使用np.signedinteger
和np.unsignedinteger
检查带符号类型或无符号类型.
Use np.signedinteger
and np.unsignedinteger
to check for signed types or unsigned types.
>>> np.issubdtype(np.uint32, np.integer)
True
>>> np.issubdtype(np.uint32, np.signedinteger)
False
>>> np.issubdtype(int, np.integer)
True
经过测试,所有浮点或复数类型都将返回False
.
All floating or complex number types will return False
when tested.
np.issubdtype(np.uint*, int)
始终为False
,因为Python int
是带符号类型.
np.issubdtype(np.uint*, int)
will always be False
because the Python int
is a signed type.
在文档此处.
这篇关于如何确定数字是否为任何类型的int(核心或numpy,带符号或非带符号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!