example:
字符串形式的"123.789"
转换成 浮点数形式的 123.789
我在这里使用了map
和reduce
上代码:
from functools import reduce def str2float(s): digitals = {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9} b = 0 # 小数位数 for i in range(len(s)): if s[i] == '.': b = len(s) - i -1 break s = s[:len(s)-b-1] + s[len(s)-b:] # str -- "123789" # print(s) # print(type(s)) def f1(s): return digitals[s] def f2(a,b): return a*10 + b def f3(s): for i in range(b): # round -- 为了 去除浮点数 运算产生的尾数,这里保存小数位 最多b位,和题目相同 s = round(s*0.1,b) return s return f3(reduce(f2,map(f1,s))) if __name__ == "__main__": a = str2float("123.789") print(a) print(type(a))
运行之后的结果是:
123.789 <class 'float'>