[英]In Python, how would you check if a number is one of the integer types?
In Python, how could you check if the type of a number is an integer without checking each integer type, ie, 'int'
, 'numpy.int32'
, or 'numpy.int64'
? 在Python中,如何在不检查每个整数类型的情况下检查数字的类型是否为整数,即
'int'
, 'numpy.int32'
或'numpy.int64'
?
I thought to try if int(val) == val
but this does not work when a float is set to an integer value (not type). 我想尝试
if int(val) == val
但是当float设置为整数值(而不是type)时,这不起作用。
In [1]: vals = [3, np.ones(1, dtype=np.int32)[0], np.zeros(1, dtype=np.int64)[0], np.ones(1)[0]]
In [2]: for val in vals:
...: print(type(val))
...: if int(val) == val:
...: print('{} is an int'.format(val))
<class 'int'>
3 is an int
<class 'numpy.int32'>
1 is an int
<class 'numpy.int64'>
0 is an int
<class 'numpy.float64'>
1.0 is an int
I want to filter out the last value, which is a numpy.float64
. 我想过滤掉最后一个值,即
numpy.float64
。
You can use isinstance
with a tuple argument containing the types of interest. 您可以将
isinstance
与包含感兴趣类型的元组参数一起使用。
To capture all python and numpy integer types use: 要捕获所有python和numpy整数类型,请使用:
isinstance(value, (int, np.integer))
Here is an example showing the results for several data types: 以下示例显示了几种数据类型的结果:
vals = [3, np.int32(2), np.int64(1), np.float64(0)]
[(e, type(e), isinstance(e, (int, np.integer))) for e in vals]
Result: 结果:
[(3, <type 'int'>, True),
(2, <type 'numpy.int32'>, True),
(1, <type 'numpy.int64'>, True),
(0.0, <type 'numpy.float64'>, False)]
A second example which is true only for int and int64: 第二个例子,仅适用于int和int64:
[(e, type(e), isinstance(e, (int, np.int64))) for e in vals]
Result: 结果:
[(3, <type 'int'>, True),
(1, <type 'numpy.int32'>, False),
(0, <type 'numpy.int64'>, True),
(0.0, <type 'numpy.float64'>, False)]
Use np.issubdtype
: 使用
np.issubdtype
:
for val in vals:
if isinstance(val, int) or np.issubdtype(val, np.int):
print('{} is an int'.format(val))
In addition to the accepted answer, the standard library also provides the numbers
module, which defines abstract classes for numerical types that can be used with isinstance
: 除了接受的答案之外,标准库还提供了
numbers
模块,它定义了可以与isinstance
一起使用的数字类型的抽象类:
isinstance(value, numbers.Integral)
This can be used to recognize both Python's int
as well as NumPy's np.int64
. 这可用于识别Python的
int
以及NumPy的np.int64
。
最简单的解决方案似乎是:
isinstance(value, (int, np.integer))
你也可以使用duck typing:
hasattr(val, "denominator") && val.denominator == 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.