python把字符串‘转换成浮点数(利用map和reduce)

冷不防 2022-11-26 09:56 233阅读 0赞

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

  1. # -*- coding: utf-8 -*-
  2. from functools import reduce
  3. def str2float(s):
  4. def f1(n1,n2):
  5. return n1*10+n2
  6. def f2(n1,n2):
  7. return n1*10+n2
  8. L=s.split(".")#将字符串按小数点分割,若为浮点类型则分割为两部分
  9. if len(L)>1:#判断是否是浮点类型
  10. a=reduce(f1,map(lambda x:int(x),L[0]))
  11. b=reduce(f2,map(lambda x:int(x),L[1]))
  12. return a+b/10**len(L[1])
  13. return reduce(f1,map(lambda x:int(x),L[0]))

测试:

  1. print('str2float(\'123.456\') =', str2float('123.456'))
  2. if abs(str2float('123.456') - 123.456) < 0.00001:
  3. print('测试成功!')
  4. else:
  5. print('测试失败!')

结果成功

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读