lambda 函数

python/lambda2026-08-24 19:46:25

lambda 函数 是一种小型、匿名的、内联函数,它可以具有任意数量的参数,但只能有一个表达式。

匿名函数不需要使用 def 关键字定义完整函数。

lambda 函数通常用于编写简单的、单行的函数,通常在需要函数作为参数传递的情况下使用,例如在 map()、filter()、reduce() 等函数中。

语法

lambda 参数1, 参数2, ... : 表达式

示例

基本用法:

add = lambda x, y: x + y
print(add(2, 3))  # 输出: 5

在列表排序中使用:

points = [(1, 2), (3, 1), (5, 0), (2, 4)]
points.sort(key=lambda point: point[1])
print(points)  # 输出: [(5, 0), (3, 1), (1, 2), (2, 4)]

在 map 函数中使用:

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # 输出: [1, 4, 9, 16]

在 filter 函数中使用:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出: [2, 4, 6]

在 reduce 函数中使用(需要导入 functools 模块):

from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 输出: 24

本页目录