Discuss / Python / str2float------coding------

str2float------coding------

Topic source

from functools import reduce DIGITS={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def str2float(s): n=0 for i in s: if i!='.': n=n+1 else: break

r1=reduce(lambda x,y:x*10+y,map(lambda s:DIGITS[s],s[:n]))
r2=reduce(lambda x,y:x*10+y,map(lambda s:DIGITS[s],s[n+1:len(s)+1]))*0.1**len(s[n+1:len(s)+1])
return r1+r2

#**:表示次方

print('str2float(\'123.456\')=',str2float('123.456')) if abs(str2float('123.456')-123.456) < 0.00001 : print('测试成功') else: print('测试失败!')


  • 1

Reply