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

10

在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类型。


如果它是一个数组(或np数据类型),您可以检查dtype。请参见https://dev59.com/1VkS5IYBdhLWcg3wJDa6。如上所述,`arr [0] .item()`将提取项目到Python数字类型。 - hpaulj
@hpaulj,我只考虑单个值,而不是数组。我在这个例子中使用了一个列表来演示。 - Steven C. Howell
单个值仍然具有 numpy 包装器。使用 item() 来移除它。 - hpaulj
@hpaulj,item()适用于numpy对象,但如果数字已经是Python数值类型,则会崩溃。它可以在try: except:子句中使用,但不能在单行if语句中使用。 - Steven C. Howell
看一下 np.float64.__mro__(以及其他 dtypes)。由于 float 在该列表中,因此 isinstance(np.float64(2), float) 返回 True - hpaulj
5个回答

23
你可以使用包含所需类型的元组参数来调用 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)]

你使用的numpy版本是什么?因为当我尝试时,得到了不同的结果。 - Francisco
np__version__ 是 1.11.2。 - dawg
@FranciscoCouzo,我和@dawg一样:np.__version__'1.11.2' - Steven C. Howell
@StevenC.Howell 是的,现在它可以工作了,最初它说的是 np.int,这给出了错误的答案。 - Francisco

10
除了被接受的答案外,标准库还提供了“numbers”模块,该模块定义了可与“isinstance”一起使用的数字类型的抽象类: numbers
isinstance(value, numbers.Integral)

这可以用来识别 Python 的 int 和 NumPy 的 np.int64


4
使用np.issubdtype:
for val in vals:
    if isinstance(val, int) or np.issubdtype(val, np.int):
        print('{} is an int'.format(val))

3
最简单的解决方案似乎是:
isinstance(value, (int, np.integer))

0
你还可以使用鸭子类型:
hasattr(val, "denominator") and val.denominator == 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接