利用map和reduce编写函数, 把字符串'123.456'转换成浮点数123.456
题目:
利用map和reduce编写一个str2float函数,
把字符串’123.456’转换成浮点数123.456
from functools import reduce
def str2float(s):
ch = {str(x): x for x in range(10)}
# 先将字符串分割
l = s.split('.')
# 将整数部分
n1 = reduce(lambda x, y: x * 10 + y, map(lambda x: ch[x], l[0]))
# 将小数部分
n2 = reduce(lambda x, y: x * 10 + y, map(lambda x: ch[x], l[1]))
n2 *= 0.1 ** len(l[1]) # a *=1 a = a*1 n2 = n2 * 0.1**4
return n1 + n2
num = str2float('123.456')
print(num)
输出结果:
123.456