Discuss / Python / 提供一个思路

提供一个思路

Topic source

coLBooy

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

1、求小数点后位数,记为count。可先将字符串反转,用[ : : -1]切片方法;再找出小数点的位置,用字符串的index方法。

2、将浮点数字符串的小数点去掉。得到“123456”,用字符串的replace方法。

3、将“123456”转换成整数123456。可继续使用上述教程中的方法。

4、用得到的整数除以10的count次幂。比如:小数点后有3位,就除以10的3次方。

def str2float(s):

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

    def char2int(c):

        return DIGITS[c]

    def fn(x,y):

        return x*10+y

    count=s[::-1].index('.')

    return reduce(fn,map(char2int,s.replace('.','')))/10**count


  • 1

Reply