Discuss / Python / 这样写是不是跟代码简洁没什么关系了。。

这样写是不是跟代码简洁没什么关系了。。

Topic source

ericwang_1992

#1 Created at ... [Delete] [Delete and Lock User]
# coding=utf-8
def str2float(string):
    def fn(x, y):
        return x * 10 + y

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

    l1, l2 = [], []
    is_before_dot = True
    for i in string:
        if i == '.':
            is_before_dot = False
            continue
        if is_before_dot:
            l1.append(i)
        else:
            l2.append(i)

    # 防止转化整形数据出错
    if len(l2) > 0:
        return reduce(fn, map(char2num, l1)) + reduce(fn, map(char2num, l2)) * 0.1 ** len(l2)
    else:
        return reduce(fn, map(char2num, l1))

print(str2float('13.43631'))

ericwang_1992

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

根据楼上的代码进行了改编,应该简洁了一些

def str2float(string):
    sn = [i for i in string if i != '.']

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

    def str2int(s):
        return reduce(lambda x, y: x * 10 + y, map(char2num, s))

    if len(string) == len(sn):
        return str2int(sn)
    else:
        return str2int(sn) * 0.1 ** (len(string)-string.index('.') - 1)

  • 1

Reply