Discuss / Python / 第二种方法浮点化字符串

第二种方法浮点化字符串

Topic source
from functools import reduce


def str2float(s):
    def char2num(x):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[x]
    n = len(s) - s.index('.') - 1  # 后面除以10的n次方
    str1, str2 = s.split('.')  # 获得'.'前后字符串
    return reduce(lambda a, b: a * 10 + b, map(char2num, str1+str2)) / (10 ** n)

  • 1

Reply