Discuss / Python / str2float(s)

str2float(s)

Topic source

竹聿Simon

#1 Created at ... [Delete] [Delete and Lock User]

from functools import reduce

def str2float(s): def char2num(s1): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s1]

def fn(x, y):
    return x * 10 + y

return reduce(fn, map(char2num, s.replace(".", "")))*(10**(-len(s[s.index(".") + 1:])))

print('str2float(\'123.456\') =', str2float('123.456'))

真是简洁易懂,大神!!!?


  • 1

Reply