Python str转float

#利用map和reduce编写一个str2float函数,把字符串‘123.456’转换成浮点数123.456
def str2float(s):
    def fn(x,y):
        return x*10+y
    n=s.index('.')
    s1=list(map(int,[x for x in s[:n]]))
    s2=list(map(int,[x for x in s[n+1:]]))
    return reduce(fn,s1)+reduce(fn,s2)/(10**len(s2))#乘幂
print('\'123.456\'=',str2float('123.456'))

 

你可能感兴趣的:(Python)