学习参考资料:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819873910807d8c322ca74d269c9f80f747330a52000
小结:
1.假设Python没有提供map()函数,请自行编写一个my_map()函数实现与map()相同的功能。
def my_map(f,lis):
from collections import Iterable
return [f(x) for x in lis if isinstance(lis,Iterable)]
#test program
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]
b = my_map(char2num,'56728')
问题:函数的参数只能有一个(或者说只能为固定值),多参数传入时不知道该如何迭代。
2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积。
def prod(lis):
return reduce(lambda x,y: x * y, lis)
#test program
prod([1,3,5,7])