Discuss / Python / 我这个应该是最简洁的了

我这个应该是最简洁的了

Topic source

-- coding: utf-8 --

from functools import reduce

def str2float(s): s1,s2=s.split('.') return (float(reduce(lambda x,y:x*10+y,map(char2num,s1+s2))))/pow(10,s.rindex('.')) 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] print('str2float(\'123.456\') =', str2float('123.456'))

尕Vimmy

#2 Created at ... [Delete] [Delete and Lock User]
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]

return reduce(lambda x, y: x + y * (0.1 ** (len(str(y)))), map(int, s.split('.')))

灰_手

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

如果可以用int和float还用得着写这么复杂么?直接一句不就结了

def str2float(s):
    return (lambda x, y='0': int(x) + int(y) * 0.1 ** len(y))(*s.split('.'))
def str2float(s):
    return float(s)

灰_手

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

还有,你们的程序处理整数时会出错。


  • 1

Reply