当前位置:首页>python>第三十四课:Python的lambda表达式

第三十四课:Python的lambda表达式

  • 2026-08-25 22:31:23
第三十四课:Python的lambda表达式
语法格式:
 lambda [parameter_list] : 表达式
  1. lambda表达式只能是单行表达式
  2. 必须使用lambda关键字定义
  3. lambda关键字之后,冒号左边的是参数列表,可以没有,也可以有多个参数。多个参数,用逗号隔开,冒号右边是该lambda表达式的返回值。
  4. 不能包含语句(如 print、return、赋值等),只能是表达式。
  5. 匿名函数:通常不赋给变量,而是直接作为参数传递给高阶函数(如 map, filter, sorted 等)。
我们先看看普通函数和lambda表达式的对比:
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]

最新文章

随机文章