python练习题4-str转float

方法1

from functools import reduce
def StrToFloat(s):
    l=s.split('.')
    return reduce(lambda x,y:int(x)+int(y)/10**len(y),l)

方法二

from functools import reduce
def StrToFloat2(s):
    def str2num(s):
        DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        return DIGITS[s]
    i = s[::-1].index('.')
    s = s.split('.')
    s1 = reduce(lambda x, y : x * 10 + y, map(str2num, s[0]))
    s2 = reduce(lambda x, y : x * 10 + y, map(str2num, s[1])) / 10**i
    return s1 + s2

测试

StrToFloat('3.1415926')

3.1415926

StrToFloat2('3.1415926')

3.1415926

posted @ 2019-05-21 23:07  babysteps  阅读(2867)  评论(0编辑  收藏  举报