在Python中,如何检查数字是否是整数类型之一?

Ste*_*ell 3 python int types numpy

在Python,你怎么能检查是否一个数的类型是不检查每个整数类型,即整型'int','numpy.int32''numpy.int64'

我想尝试if int(val) == val但是当float设置为整数值(不是类型)时,这不起作用.

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
Run Code Online (Sandbox Code Playgroud)

我想过滤掉最后一个值,这是一个numpy.float64.

daw*_*awg 7

您可以使用isinstance包含感兴趣类型的元组参数.

要捕获所有python和numpy整数类型,请使用:

isinstance(value, (int, np.integer))
Run Code Online (Sandbox Code Playgroud)



以下示例显示了几种数据类型的结果:

vals = [3, np.int32(2), np.int64(1), np.float64(0)]
[(e, type(e), isinstance(e, (int, np.integer))) for e in vals]
Run Code Online (Sandbox Code Playgroud)

结果:

[(3, <type 'int'>, True), 
 (2, <type 'numpy.int32'>, True), 
 (1, <type 'numpy.int64'>, True), 
 (0.0, <type 'numpy.float64'>, False)]
Run Code Online (Sandbox Code Playgroud)


第二个例子,仅适用于int和int64:

[(e, type(e), isinstance(e, (int, np.int64))) for e in vals]
Run Code Online (Sandbox Code Playgroud)

结果:

[(3, <type 'int'>, True), 
(1, <type 'numpy.int32'>, False), 
(0, <type 'numpy.int64'>, True), 
(0.0, <type 'numpy.float64'>, False)]
Run Code Online (Sandbox Code Playgroud)


小智 6

除了接受的答案之外,标准库还提供了numbers模块,该模块定义了数字类型的抽象类,可用于isinstance

isinstance(value, numbers.Integral)
Run Code Online (Sandbox Code Playgroud)

这可用于识别 Pythonint和 NumPy 的np.int64.