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'))

猜你喜欢

转载自blog.csdn.net/zoujin6649/article/details/81133294