1 from functools import reduce 2 def str2float(s): 3 def char2num(s): 4 digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':11}
#11只是一个标记 5 return digits[s] 6 r=list(map(char2num,s)) 7 8 def plus(x,y): 9 if y!=11: 10 return x*10+y 11 else: 12 return x 13 return reduce(plus,r)*10**-(len(s)-s.index('.')-1)
学习代码
1 def char2num(s): 2 digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} 3 return digits[s]
#计算小数点位数 4 dot=len(s)-s.index('.')-1
#将小数点替换掉 5 new_s=s.replace('.','') 6 r=list(map(char2num,new_s)) 7 def plus(x,y): 8 return x*10+y 9 return reduce(plus,r)*10**-dot