Discuss / Python / 关键在于使用s.index()方法找到小数点的索引值,使用for循环字符串太麻烦了

关键在于使用s.index()方法找到小数点的索引值,使用for循环字符串太麻烦了

Topic source

def str2float(s):

    D = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

    i = s.index('.') # 得到小数点的索引值

    s1 = s[:i] # 将字符串以小数点分隔开

    s2 = s[i+1:]

    def chr_to_num(ch): # 将字符格式的数字转换为数字格式

        return D[ch]

    n1 = reduce(lambda x,y: x*10+y, map(chr_to_num, s1))

    n2 = reduce(lambda x,y: x*10+y, map(chr_to_num, s2))/(10**len(s2))

    return n1+n2

太聪明了,学习了


  • 1

Reply