def str2float(s):
if not isinstance(s, str):
raise TypeError('Parameter must be str') #判断字符串是否可以迭代
if '.' not in s:
return int(s) #判断字符串是否是整数,如果是整数,则直接返回
int_str, float_str = s.split('.') #用‘.’分割S为int_str和float_str
return reduce(lambda x, y: x 10 + y, map(char2num, int_str + float_str)) / (10 * len(float_str))
爱美食的Y先生
第一个:
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
#2017年10月11日14:04:54
#* coding: utf-8 * from functools import reduce def str2float(s): def fn(x ,y): return x 10 + y def char2num(ch): return{'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[ch] L = s.split('.') #利用'.'将L字符分割成两个字符串
L1 = reduce(fn ,map(char2num,L[0])) L2 = reduce(fn ,map(char2num,L[1]))/(10 *len(L[1])) return L1 + L2 print('str2float(\'123.456\')=',str2float('123.456'))
#输出为:
#str2float('123.456')= 123.456
#总结:
#reduce的‘累积’功能并不是连乘,而是累加
#L1 = reduce(fn ,map(char2num,L[0])) 是现将L[0]中的数列带入char2num中,
#map得到一个可迭代数列,然后再讲数列依次带入fn中,然后由reduce实现数列
#内的累加
第二种:
#利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
#2017年10月11日14:38:37
#此代码加入整数判断
-- coding: utf-8 --
from functools import reduce
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 str2float(s): if not isinstance(s, str): raise TypeError('Parameter must be str') #判断字符串是否可以迭代 if '.' not in s: return int(s) #判断字符串是否是整数,如果是整数,则直接返回 int_str, float_str = s.split('.') #用‘.’分割S为int_str和float_str return reduce(lambda x, y: x 10 + y, map(char2num, int_str + float_str)) / (10 * len(float_str))
print('str2float(\'123.456\') =', str2float('123.456'))
#输出为:
#str2float('123.456') = 123.456
#个人觉得此处的整数判断是多余的