Discuss / Python / 不需要分割的做法

不需要分割的做法

Topic source
def char2num(s):
    return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'.':None}[s]
n = [i for i,x in enumerate(s) if x == '.'][0]
L = list(map(char2num,s))
L.pop(n)   
return reduce(lambda x,y: x*10+y , L)/(10**n)

叫我状爷

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

雨情雾语

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

写的很好,非常简练,就是稍微有点小问题; n是代表小数点在字符串中的索引,最终结果除以10的n次方是有问题的,小数点后面有几个数字应该除以10的几次方,只是这个实例中刚好小数点前后的位数一样多,所以你的输出结果正确

你可以试验一下 print('str2float(\'12.3456\') =', str2float('12.3456'))或者 print('str2float(\'1234.56\') =', str2float('1234.56'))

稍作修改: 获取索引n = [i for i,x in enumerate(s) if x == '.'][0] 可以用 n = s.index('.')代替

最后一句改为:return reduce(lambda x,y: x10+y , L)/10*(len(s)-n-1)

def char2num(s):
    return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'.':None}[s]
n = s.index('.')
L = list(map(char2num,s))
L.pop(n)   
return reduce(lambda x,y: x*10+y , L)/10**(len(s)-n-1)

补充几个语法:

Array.index: Return the smallest i such that i is the index of the first occurrence of x in the array.
Lambda expressions (sometimes called lambda forms) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with:

def name(arguments):
    return expression

  • 1

Reply