Discuss / Python / 字符串转浮点数

字符串转浮点数

Topic source

叫小小兽

#1 Created at ... [Delete] [Delete and Lock User]
def str2float(s):
    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 fn(x,y):
        return x*10+y
    temp=s.split('.')
    #整数位
    int_num=reduce(fn,map(char2num,temp[0]))
    #小数位
    l=len(temp[1])
    float_num=(reduce(fn,map(char2num,temp[1])))/(10**l)
    return int_num+float_num

rain-rhythm

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

from functools import reduce def str2float(s): 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 f(x,y): return x10+y temp=s.split('.') int_num=reduce(f,map(char2num,temp[0]) float_num = (reduce(f,map(char2num,temp[1]))/10*len(temp[1]) return int_num+float_num print('str2float(\'123.456\') =', str2float('123.456'))

提示: float_num = (reduce(f,map(char2num,temp[1]))/10**len(temp[1]) ^ SyntaxError: invalid syntax 为什么呀


  • 1

Reply