0
import numpy as np 
import sklearn 
import sklearn.datasets
from sklearn import svm
x = np.array([1,3,67,8])
print(x)
print(type(x))

if type(x) != int:
    y = x.astype(int)
    print(y)
    print(type(y))
else:
    print ("X is already an integer")

这是我的代码,如果x不是整数,则将其转换为整数,否则将其打印为整数,但奇怪的是,if即使x是整数或浮点数,语句中的代码也会执行。

4

1 回答 1

1

我相信这就是您正在寻找的。要检查值是否为整数(即​​使在float数组中),您可以测试x == int(x).

import numpy as np 

arr = np.array([1, 3, 67, 8, 7.5])

print(arr, type(arr))

for x in arr:
    if x != int(x):
        y = x.astype(int)
        print(y, type(y))
    else:
        print(str(int(x)) + ' is already an integer')

# [  1.    3.   67.    8.    7.5] <class 'numpy.ndarray'>
# 1 is already an integer
# 3 is already an integer
# 67 is already an integer
# 8 is already an integer
# 7 <class 'numpy.int32'>
于 2018-02-04T11:48:18.047 回答