python lambda

1、lambda是什么?



    看个例子:     



g = lambda x:x+1
  看一下执行的结果: 



  g(1)



  »>2



  g(2)



  »>3



  当然,你也可以这样使用:



  lambda x:x+1(1)



  »>2   



  可以这样认为,lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体,用函数来表示为:



def g(x):
return x+1
  非常容易理解,在这里lambda简化了函数定义的书写形式。是代码更为简洁,但是使用函数的定义方式更为直观,易理解。



Python中,也有几个定义好的全局函数方便使用的,filter, map, reduce  



复制代码





foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]



print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]



print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]



print reduce(lambda x, y: x + y, foo)
139






https://www.cnblogs.com/evening/archive/2012/03/29/2423554.html
https://www.cnblogs.com/mxh1099/p/5386529.html
https://zhuanlan.zhihu.com/p/80960485?utm_source=wechat_timeline


Category python