Discuss / Python / 记录一下

记录一下

Topic source

XHS_12302

#1 Created at ... [Delete] [Delete and Lock User]
# _*_ coding: utf-8 _*_
# 如果字符串元素中有重复的,这个不太适用


def str2float2(s):
    return reduce(lambda a, b: a * 10 + b if s.index('.') - s.index(str(b)) > 0 else ( a if s.index('.') - s.index(str(b)) == 0 else a + b * 0.1 ** (s.index(str(b)) - s.index('.'))),                  map(lambda v: int(v) if v != '.' else '.', s))

XHS_12302

#2 Created at ... [Delete] [Delete and Lock User]
# _*_ coding: utf-8 _*_
# 普通解决


def str2float(s):
    base = 10
    sum_ = 0
    flag = True
    for v in s:
        if v == '.':
            base = 0.1
            flag = False
            continue
        sum_ = sum_ * base + int(v) if flag else sum_ + int(v) * base
        base = base * 0.1 if not flag else base
    return sum_

  • 1

Reply