map
- 接收两个参数,一个是函数,一个是列表
- 将该函数逐个作用于列表中的所有元素
- 返回一个迭代器
map(f, [x1, x2, x3, x4]) = [f(x1), f(x2), f(x3), f(x4)]
f(x) = x * x││┌───┬───┬───┬───┼───┬───┬───┬───┐│ │ │ │ │ │ │ │ │▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼[ 1 2 3 4 5 6 7 8 9 ]│ │ │ │ │ │ │ │ ││ │ │ │ │ │ │ │ │▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼[ 1 4 9 16 25 36 49 64 81 ]
reduce
- 接收两个参数,一个是函数f,一个是列表
- f 接收两个参数
- reduce 依次将结果和列表中下一个元素传到 f 中计算
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
练习
一,利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
def normalize(name):return name[0].upper()+name[1:].lower()
二,Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
def prod(L):return reduce(lambda x,y:x*y,L)
三,利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
def str2float(s):a,b=s.split('.')a1=reduce(lambda x,y:10*x+y,map(int,a))b1=reduce(lambda x,y:0.1*x+y,map(int,b[::-1]))/10return a1+b1
