python匿名函数lambda_python学习笔记10-匿名函数lambda

匿名函数lambda

定义匿名函数

lambda

def fun(x,y):

return x*y

r=lambda x,y: x*y

r(3,4)In [2]: r = lambda x, y: x *y

In [3]: r(3,4)

Out[3]: 12

lambda基础

lambda语句中,冒号前是参数,可以有多个,逗号隔开,冒号右边是返回值

lambda语句构建的其实是一个函数的对象

lambda匿名函数的优点:

1、使用python写一写脚本的时候,使用lambda可以省去定义函数的过程,让代码更加精简

2、对于一些抽象的,不会别别的地方再重复使用的函数,有时候函数起个名字也是难题,使用lambda不需要考虑命名的问题

3、使用lambda在某些时候让代码更容易理解

reduce的用法:

就是通过function()函数去处理sequence序列,reduce内部的function()必须是二元的计算,二元加减乘除

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates处理过程: ((((1+2)+3)+4)+5)

help(reduce)reduce(...)

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,

from left to right, so as to reduce the sequence to a single value.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates

((((1+2)+3)+4)+5). If initial is present, it is placed before the items

of the sequence in the calculation, and serves as a default when the

sequence is empty.

(END)

In [8]: def add(x,y):

...: return x+y

...:

In [9]: reduce(add,range(1,101)) # 1+2+3+4+5+......100=5050

Out[9]: 5050

In [10]: reduce(lambda x,y:x+y,range(1,101))# 1+2+3+4+5+......100=5050

Out[10]: 5050

In [11]: reduce(lambda x,y:x*y,range(1,6)) # 5*4*3*2*1

Out[11]: 120

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值