map函数
def f(x):
return x*x
r = map(f, [1, 2, 3, 4, 5])
list(r)
reduce函数
from functools import reduce
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
组合使用
from functools import reduce
def str2int(s):
def fn(x, y):
return x * 10 + y
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(fn, map(char2num, s))
测试
测试1
利用map函数,将输入的不规范的英文名字输出为规范的英文名字
def normalize(name):
return name.capitalize()
if __name__ == "main":
L1 = ['sdhi', 'HFIS', 'bsiH']
L2 = list(map(normalize, L1))
print(L2)
测试2
求累积
from functools import reduce
def prod(L):
return reduce(lambda x, y : x * y, L)
测试3
利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456:
from functools import reduce
def str2float(s):
def change(ss):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.' : None}[ss]
ins = 0
for str in s:
ins += 1
if(str == '.'):
break
return reduce(lambda x, y: x * 10 + y, [re for re in list(map(change, s)) if re != None]) / (10 ** (len(s) -ins ))