在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)]

08-18 16:40
查看更多