from functools import reduce
def str2float(s):
L=s.split('.');
def str2float(s):
L=s.split('.');
return reduce(lambda x,y:y+x*10,map(int,L[0]))+reduce(lambda x,y:y+x*10,map(int,L[1]))/10**len(L[1])
方法2:
from functools import reduce
def str2float(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
s=s.split('.') #split('.')将字符串按‘.’分隔开
n=s[0]+s[1] #连接两个字符串,整体转换
return reduce(lambda x,y:x10+y,map(char2num,n))/(10*len(s[1]))
本文介绍两种将字符串转换为浮点数的方法。第一种使用reduce和map函数分别处理小数点前后的数字部分;第二种则先将整数和小数部分合并再进行转换,并通过reduce实现。
2890

被折叠的 条评论
为什么被折叠?



