【发布时间】:2017-05-09 11:35:15
【问题描述】:
对于 Python 课程,我希望得到您的帮助。
定义一个函数 check_conversion,它接受两个参数:一个数组和一个数据类型。该函数应返回一个布尔值,指示初始数组中的所有元素是否可以无损地转换为指定的数据类型。
现在我得到了这段代码,但它在每次输入时都返回 True。我们只能使用 numpy 库,所以这是一个约束。 我可能想多了,会有一个更简单的解决方案。
import numpy
def check_conversion(x, d_type):
x = numpy.array([x], dtype= d_type)
dtype = ""
x_float32 = x.astype('float32')
x_float64 = x.astype('float64')
x_int = x.astype('int')
x_un_int64 = x.astype('uint64')
print(x, x.dtype)
print(x_int, x_int.astype)
print(x_float32, x_float32.dtype)
if numpy.all(x) == numpy.all(x_float32):
return True
elif numpy.all(x) == numpy.all(x_float64):
return True
elif numpy.all(x) == numpy.all(x_int):
return True
elif numpy.all(x) == numpy.all(x_un_int64):
return True
else:
return False
a = numpy.array([3., 3.2, 1])
data_type_a = "int"
print(check_conversion(a, data_type_a))
b = numpy.array([3., 3.2, -1])
data_type_b = "float32"
print(check_conversion(b, data_type_b))
c = numpy.array([3., 3.2, -1])
data_type_c = "float64"
print(check_conversion(c, data_type_c))
d = numpy.array([3, 2, -1])
data_type_d = "uint64"
print(check_conversion(d, data_type_d))
提前致谢!
【问题讨论】:
-
你能修复一下缩进吗?
-
嗨,我猜你误解了
np.all的工作原理。如果数组的所有元素都是True,它给出True,否则给出False。这里0和0.0被认为是False,所有其他数字被认为是True。您的比较仅检查两个数组是否包含零。您需要将条件更改为numpy.all(x==x_float32)。此外,您只想检查函数调用中给出的数据类型。 Atm 你只检查float32,如果这有效,给Trueend 继续检查elseway。
标签: python arrays numpy type-conversion