Discuss / Python / 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

Topic source

翘首以盼_

#1 Created at ... [Delete] [Delete and Lock User]
from functools import reduce

def str2float(s):

    def f(x, y):
        return x * 10 + y

    def itg(b):
        return 10 ** len(b)

    point = s.find('.')

    front = s[:point]
    back  = s[point+1:]

    reduceF = reduce(f, map(int, front))
    reduceB = reduce(f, map(int, back))

    back_reduce_B = reduceB / itg(back)
    last_result = reduceF + back_reduce_B

    print(last_result)

str2float('123.456')
str2float('456.123')
str2float('332.789')

  • 1

Reply