在 Python 中,如何检查一个数字是否是整数类型之一?
·
问题:在 Python 中,如何检查一个数字是否是整数类型之一?
在 Python 中,如何在不检查每个整数类型(即'int'
、'numpy.int32'
或'numpy.int64'
)的情况下检查数字的类型是否为整数?
我想尝试if int(val) == val
但这在将浮点数设置为整数值(不是类型)时不起作用。
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
我想过滤掉最后一个值,即numpy.float64
。
解答
您可以将isinstance
与包含感兴趣类型的元组参数一起使用。
要捕获所有 python 和 numpy 整数类型,请使用:
isinstance(value, (int, np.integer))
以下示例显示了几种数据类型的结果:
vals = [3, np.int32(2), np.int64(1), np.float64(0)]
[(e, type(e), isinstance(e, (int, np.integer))) for e in vals]
结果:
[(3, <type 'int'>, True),
(2, <type 'numpy.int32'>, True),
(1, <type 'numpy.int64'>, True),
(0.0, <type 'numpy.float64'>, False)]
第二个示例仅适用于 int 和 int64:
[(e, type(e), isinstance(e, (int, np.int64))) for e in vals]
结果:
[(3, <type 'int'>, True),
(1, <type 'numpy.int32'>, False),
(0, <type 'numpy.int64'>, True),
(0.0, <type 'numpy.float64'>, False)]
更多推荐
目录
所有评论(0)