您的位置:首页 > 编程语言 > Python开发

python --如何利用map+reduce 将一个字符串转成浮点型

2019-04-19 17:44 225 查看

from functools import reduce 
def str2float(s):
    def dict(s):
        dict1 ={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':'.'}
        return dict1[s]  
    def fn(x,y):
        return x*10+y
    a =0
    for i in s :
        a +=1
        if i =='.':
            s = s[:a-1]+s[a:]
            break
    if a ==len(s):
        return reduce(fn,map(dict,s))
    else:
        return reduce(fn,map(dict,s))/(10**(len(s)-a+1))

验证:

m='123.456'
print(str2float(m))

输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐