码迷,mamicode.com
首页 > 其他好文 > 详细

匿名函数、函数式函数

时间:2020-01-20 00:00:48      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:append   执行   pre   功能   app   函数   没有   定义   add   

  匿名函数用来进行简单的重复操作,在没有必要单独定义参数的情况下,可以使用匿名函数lambda。

例如:

def fun(x):

  return x+1

使用匿名函数可以定义为

lambda x:x+1

匿名函数在单独存在的情况下可以用如下方式使用:

a= lambda a,b,c:(a+1,b+2,c+3)

print(a(1,2,3))

使用函数调用函数来输出不同功能:

def add_one(x):
return x+1
def red_one(x):
return x-1
def mac_one(x):
return x**2
def map_test(func,x):
ret=[]
for i in x:
res=func(i)
ret.append(res)
return ret
x=[1,2,3,4]
print(map_test(add_one,x))
print(map_test(red_one,x))
print(map_test(mac_one,x))

执行结果为:

[2, 3, 4, 5]
[0, 1, 2, 3]
[1, 4, 9, 16]

Process finished with exit code 0

使用匿名函数代码可以写为以下:

def map_test(func,x):
ret=[]
for i in x:
res=func(i)
ret.append(res)
return ret
x=[1,2,3,4]

print(map_test(lambda x:x+1,x))
print(map_test(lambda x:x-1,x))
print(map_test(lambda x:x**2,x))

匿名函数、函数式函数

标签:append   执行   pre   功能   app   函数   没有   定义   add   

原文地址:https://www.cnblogs.com/sxdx1023/p/12215775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!