Discuss / Python / 第三题

第三题

Topic source
def str2float(s):
    d = 1
    i = s[::-1].find('.') - 1
    while i != -1:
        i -= 1
        d *= 10
    num = reduce(lambda x, y: x * 10 + y, map(
        lambda x: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[x], [x for x in s if
                                                                                                        x not in '.-'])) / d
    return 0 == s.find('-') and -num or num

只能处理正常的数值字符串

def str2float(s):
    d = 1
    i = s[::-1].find('.') - 1
    while i > 0:
        i -= 1
        d *= 10
    num = reduce(lambda x, y: x * 10 + y, map(
        lambda x: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[x], [x for x in s if
                                                                                                        x not in '.-'])) / d
    return 0 == s.find('-') and -num or num
def str2float(s):
    i = s[::-1].find('.')
    num = reduce(lambda x, y: x * 10 + y, map(
        lambda x: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[x], [x for x in s if
                                                                                                        x not in '.-'])) / (i > 0 and 10**i or 1)
    return 0 == s.find('-') and -num or num

  • 1

Reply