1. 利用mapreduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

from functools import reduce
def str2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2float(s):
    if '.' in s:
        # 将字符串s拆分成list类型
        s = s.split('.')
        # 通过小数点分割,分别计算然后相加
        return reduce(lambda x, y: x*10+y, map(str2num,s[0])) + reduce(lambda x, y: x/10+y, map(str2num, s[1][::-1]))/10
    else:
        return  reduce(lambda x, y: x*10+y, map(str2num, s))
s1 = str2float('123.456')
print(s1)
View Code

相关文章: