如何确定数字是否为任何类型的int(核心或numpy,带符号或非带符号)? [英] How to determine if a number is any type of int (core or numpy, signed or not)?

查看:129
本文介绍了如何确定数字是否为任何类型的int(核心或numpy,带符号或非带符号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试变量是否为类型intnp.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)仅匹配intnp.int32(或np.int64取决于平台),
  • np.issubdtype(type(n), int)似乎与所有intnp.int*都匹配,但与np.uint*不匹配.
  • isinstance(n, int) will only match int and np.int32 (or np.int64 depending on plateform),
  • np.issubdtype(type(n), int) seems to match all int and np.int*, but doesn’t match np.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.signedintegernp.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,带符号或非带符号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆