lambda [parameter_list] : 表达式- lambda关键字之后,冒号左边的是参数列表,可以没有,也可以有多个参数。多个参数,用逗号隔开,冒号右边是该lambda表达式的返回值。
- 不能包含语句(如 print、return、赋值等),只能是表达式。
- 匿名函数:通常不赋给变量,而是直接作为参数传递给高阶函数(如 map, filter, sorted 等)。
def add(x, y): return x+ y# 改造后a = lambda x, y: x + y
例如:上节课的局部函数,改造成lambda表达式(原函数如下)def get_math_func(type) : # 定义一个计算平方的局部函数 def square(n) : # ① return n * n # 定义一个计算立方的局部函数 def cube(n) : # ② return n * n * n # 定义一个计算阶乘的局部函数 def factorial(n) : # ③ result = 1 for index in range(2 , n + 1): result *= index return result # 返回局部函数 if type == "square" : return square if type == "cube" : return cube else: return factorial# 调用get_math_func(),程序返回一个嵌套函数math_func = get_math_func("cube") # 得到cube函数print(math_func(5)) # 输出125math_func = get_math_func("square") # 得到square函数print(math_func(5)) # 输出25math_func = get_math_func("other") # 得到factorial函数print(math_func(5)) # 输出120
def get_math_func(type) : result=1 # 该函数返回的是Lambda表达式 if type == 'square': return lambda n: n * n # ① elif type == 'cube': return lambda n: n * n * n # ② else: return lambda n: (1 + n) * n / 2 # ③# 调用get_math_func(),程序返回一个嵌套函数math_func = get_math_func("cube")print(math_func(5)) # 输出125math_func = get_math_func("square")print(math_func(5)) # 输出25math_func = get_math_func("other")print(math_func(5)) # 输出15.0
lambda表达式调用Python内置map()函数:# 传入计算平方的lambda表达式作为参数x = map(lambda x: x*x , range(8))print([e for e in x]) # [0, 1, 4, 9, 16, 25, 36, 49]# 传入计算平方的lambda表达式作为参数y = map(lambda x: x*x if x % 2 == 0 else 0, range(8))print([e for e in y]) # [0, 0, 4, 0, 16, 0, 36, 0]