我有一个函数需要输入 float 类型以进行进一步计算。 不幸的是,输入类型包括:
列表floatnumpy.array
我对我的解决方法不满意,我想知道是否有更好的解决方案。
def get_correct_float(x):
try:
if len(x) == 1:
return x[0]
except:
return x
a = [.5]
b = .5
c = np.array([.5])
get_correct_float(a) == get_correct_float(b) == get_correct_float(c)
TRUE
get_correct_float(a)
0.5
请您参考如下方法:
使用isinstance ,
>>> import numpy as np
>>> l = [[.5], .5, np.array([.5])]
>>> f = [x if isinstance(x, float) else x[0] for x in l]
>>> f
[0.5, 0.5, 0.5]
def get_correct_float(x):
return x if isinstance(x, float) else x[0]
以前的回答,
import numpy as np
def get_correct_float(x):
if isinstance(x, list):
return x[0]
elif isinstance(x, np.ndarray):
return x[0]
else:
return x
