首页 > 其他 > 详细

高阶函数:map,reduce

时间:2015-11-18 19:28:06      阅读:277      评论:0      收藏:0      [点我收藏+]
  • map形式:map(f,List)
  • 作用:f为一个函数,List为一序列,map将传入的函数依次作用到List的每个元素,并把结果作为性的List返回。
  • reduce形式:reduce(f,List)
  • 作用:将List的前两个元素作用于f,求得的结果与List的下一个元素继续作用于f,依次进行,故f必须为接收两个参数的函数,即reduce(f,[a,b,c,d])=f(f(f(a,b),c),d)
 1 #-*-coding:utf-8-*-
 2 #首字母大写,其他小写
 3 def toCapitalize(s):
 4     return s.capitalize()
 5 
 6 S = [adam,LISA,barT]
 7 print map(toCapitalize,S)
 8 
 9 #对一个List求积
10 def prod(li):
11     # def multi(a,b):
12     #     return a*b
13     # return reduce(multi,li)
14     return reduce(lambda x,y:x*y,li)
15 Li = [3,4,5]
16 print prod(Li)
17 
18 #str2int的实现
19 def str2int(s):
20     def char2num(chr):
21         return {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}[chr]
22     return reduce(lambda x,y : x*10+y ,map(char2num,s))
23 St= 17362
24 print str2int(St)

运行结果:

[Adam, Lisa, Bart]
60
17362

 

高阶函数:map,reduce

原文:http://www.cnblogs.com/chenxy93/p/4975567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!