from functools import reduce def str2float(s): p = 0 q = 1 if s[0] == '-': s = s[1:] p = -1 for i in range(len(s)): if s[i] == '.': s = s[:i]+s[i+1:] q = len(s) - i break def fn(x, y): return x * 10 + y
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] return reduce(fn, map(char2num, s)) / (10 ** q) * p
print('str2float(\'123.456\') =', str2float('123.456'))
我知道了,p刚开始要设为1
Sign in to make a reply
巴黎的雨_l
from functools import reduce def str2float(s): p = 0 q = 1 if s[0] == '-': s = s[1:] p = -1 for i in range(len(s)): if s[i] == '.': s = s[:i]+s[i+1:] q = len(s) - i break def fn(x, y): return x * 10 + y
print('str2float(\'123.456\') =', str2float('123.456'))