Using a map and reduce write function, the string '123.456' into float 123.456

Using a map and reduce write function, the string '123.456' into float 123.456

Title:
using a map and reduce str2float write function,
the string '123.456' into float 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)

Output:

123.456
Published 60 original articles · won praise 6 · views 1327

Guess you like

Origin blog.csdn.net/weixin_45775963/article/details/103733598