Discuss / Python / 字符串'123.456'转换成浮点数123.456的作业

字符串'123.456'转换成浮点数123.456的作业

Topic source

烈可烈

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

简单粗暴的思路,就是把小数变成整数,回头再除过去,比如说‘0.1’变成1,回头再除以10,变成0.1,好处就是有没有小数点都可以共用一套模板。缺点就是假如小数点后面非常非常多位的话,那么变成整数,就会溢出了。

def str2float(s):
    # 字符串转成list
    L_str = [c for c in s]
    # 交给map转成数字型的list
    L_num = test_m(L_str)
    # 最后转成数字
    return test_r2(L_num)

下面是map相关的方法 DIGITS_NUM = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}

def charToNum(key):
    return DIGITS_NUM.get(key) 

def test_m(L):
    return list(map(charToNum, L))

下面是把数字型的list转换成数字的操作

def test_r2(L):
    if not isinstance(L, list):
        raise RuntimeError('只允许list')

    try:
        # 取出小数点的坐标
        i = L.index('.', 1, -1)
        # print('小数点位置 = ', i)
        L.remove('.')
        return test_r(L) / (10 ** (len(L) - i))
    except ValueError as e:
        # print('列表里没有小数点')
        return reduce(numListToNumForInt, L)

  • 1

Reply