Python之匿名函数

匿名函数

  基本格式:lambda 变量 : 函数式(返回值),示例:

fun=lambda x: x*2
'''
等价于
fun(x):
    return x*2
'''
res = fun(3)
print(res)
#--------------
6

  返回多个值以元组封装形式返回:

fun=lambda x,y:(x+y,x*y)

res = fun(4,5)
print(res)
#------------------------
(9, 20)

  使用匿名函数时,常将函数地址以参数形式传给其他函数,共其调用,示例:

def fun(func,x):
ret = func(x) #获取func地址,并执行
return ret res = fun(lambda x:x+4,8) print(res) #------------------------------ 12

 

posted @ 2018-09-06 15:57  恋853雨  阅读(129)  评论(0编辑  收藏  举报