from functools import reduce
di = {}
di.update(zip(‘1234567890.‘, [1,2,3,4,5,6,7,8,9,0,‘.‘]))
def str2float(s):
st = s.split(‘.‘)
st1 = reduce(lambda x,y: 10*x + y, map(lambda x: di[x], st[0]))
try:
st2 = reduce(lambda x,y: (x*0.1 + y), map(lambda x: di[x], st[1][::-1]))/10
#st2 = reduce(lambda x,y: (x*0.1 + y), map(lambda x: di[x]/10, st[1][::-1])) #也可以在取数的时候变成一个一位小数
except:
st2=0
return st1 + st2
st = ‘123.456‘
a = str2float(st)
print(a, type(a))
运行结果:
123.456 <class ‘float‘>
原文地址:https://www.cnblogs.com/guiyuhua/p/8641490.html
时间: 2024-11-06 21:18:35