匿名函数、函数式函数

  匿名函数用来进行简单的重复操作,在没有必要单独定义参数的情况下,可以使用匿名函数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))

猜你喜欢

转载自www.cnblogs.com/sxdx1023/p/12215775.html