字符串转浮点数 str2float (python版本)

来源:互联网 发布:java web im 开源 编辑:程序博客网 时间:2024/05/20 17:28

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

# -*- coding: utf-8 -*-from functools import reducedef str2float(s):    def char2num(s):        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]    n = s.index('.')    return reduce(lambda x,y:x*10+y,map(char2num,s[:n]+s[n+1:]))/(10**n)

print('str2float(\'123.456\') =', str2float('123.456'))

思路:char2num函数用来将字符串转化为int,然后我们跳过小数点,将123.456变为123456,再用reduce函数 把它们变为整数,最后除以10^n 即可得到对应的小数

0 0