# !/usr/bin/python3 # -*-coding:UTF-8-*- # FileName: func_str2float.py from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} str2int = lambda s: reduce(lambda x, y: x * 10 + y, map(lambda c: DIGITS[c], s)) def str2float(s): ''' 利用map和reduce编写一个str2float函数, 把字符串'123.456'转换成浮点数123.456 ''' tup = s.partition(".") #返回3元的元组: (左边的子串,分隔符,右边的子串) num = float(f'{str2int(tup[0])}.{str2int(tup[2])}') return num if __name__ == '__main__': print('str2float(\'123.456\') =', str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('测试成功!') else: print('测试失败!')
Sign in to make a reply
ywjco_567