If-Else 语句在 Python 中工作很奇怪
If-Else statement works weird in Python
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
不是整数,则将其转换为整数,否则将其打印为整数,但它的工作很奇怪,即使 x
语句中的代码也会执行] 是整数或浮点数。
我相信这就是您要找的。要检查一个值是否为整数(即使在 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'>
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
不是整数,则将其转换为整数,否则将其打印为整数,但它的工作很奇怪,即使 x
语句中的代码也会执行] 是整数或浮点数。
我相信这就是您要找的。要检查一个值是否为整数(即使在 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'>