1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 【Python】利用map和reduce编写一个str2float函数 把字符串'123.456'转换成浮点数123.456

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

时间:2022-03-18 02:33:00

相关推荐

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

微信公众号

题目来源:【廖雪峰的官方网站-map/reduce】

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

from functools import reduceCHAR_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 ch: CHAR_TO_FLOAT[ch], s)point = 0def to_float(f, n):nonlocal pointif n == -1:point = 1return fif point == 0:return f * 10 + nelse:point = point * 10return f + n / pointreturn reduce(to_float, nums, 0.0)print('str2float(\'123.456\') =', str2float('123.456'))if abs(str2float('123.456') - 123.456) < 0.00001:print('测试成功!')else:print('测试失败!')

代码参考:/michaelliao/learn-python3/blob/master/samples/functional/do_reduce.py

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。