首页 > 其他 > 详细

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

时间:2017-02-06 17:11:09      阅读:451      评论:0      收藏:0      [点我收藏+]
from functools import reduce
CHAR_TO_FLOAT = {
    0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9,
    .: -1
}
def str2float(s):
    nums=map(lambda x:CHAR_TO_FLOAT[x],s)
    #print(list(nums))
    point = 0

    def str_division(f,n):
        nonlocal point
        if n == -1:
            point = 1
            return f
        if point == 0:
            return f * 10 + n
        else:
             point = point * 10
             return f + n / point
    return reduce(str_division,nums)

print(str2float(123.456))

 

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

原文:http://www.cnblogs.com/python3-study/p/6370869.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!