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

Phoebe ·
更新时间:2024-09-20
· 518 次阅读

题目来源:廖雪峰的官方网站
python初学者,求轻喷

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

这道题我想到两种思路
1.读取str中的数字和小数点位置,先将其转换为整数然后除以小数点的位置
2.将str中小数部分和整数部分分别还原,最后相加

对于方法二,在实际操作中我想不到能够同时还原小数部分和整数部分的函数,故舍弃,采用方法一

# -*- coding: utf-8 -*- from functools import reduce def str2float(s): 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 is_point(s): return s != -1 #消除小数点 def fn(x,y): return x*10+y #还原成整数 def STR_TO_NUM(s): return CHAR_TO_FLOAT[s] #将字符串转换为数字list L=list(map(STR_TO_NUM,s)) digit=len(L)-L.index(-1)-1 L=list(filter(is_point,L)) return reduce(fn,L)/pow(10,digit) print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')
作者:SYRUPyer



str reduce map float 字符串 浮点数 Python 字符 浮点

需要 登录 后方可回复, 如果你还没有账号请 注册新账号