Discuss / Python / 来做题 （爱上用匿名函数了，简洁明了！）

### 来做题 （爱上用匿名函数了，简洁明了！）

Topic source

#### 拖延症↘患者

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

from functools import reduce

d={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def str2float(s):

int_1=reduce(lambda x,y:x*10+y,map(lambda s:d[s],s[:s.find('.')]))

float_1=reduce(lambda x,y:(x*10+y),map(lambda s:d[s],s[s.find('.')+1:]))*0.001

return int_1+float_1

#测试

print('str2float(\'123.456\') =', str2float('123.456'))

if abs(str2float('123.456') - 123.456) < 0.00001:

print('测试成功!')

else:

print('测试失败!')

#### 拖延症↘患者

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

#修改成实现任意位小数转换。

from functools import reduce

d={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}

def str2float(s):

int_1=reduce(lambda x,y:x*10+y,map(lambda s:d[s],s[:s.find('.')]))

float_1=reduce(lambda x,y:(x*10+y),map(lambda s:d[s],s[s.find('.')+1:]))*(1/10**(len(s)-s.find('.')-1))

return int_1+float_1

#测试

ret=str2float('12345.6')

print(ret)

• 1