Lambda
一句话解释
lambda 是 小 anonymous 函数 定义 in 单个 表达式, 编写 as lambda params: 表达式.
用大白话说
lambda 是 anonymous (nameless) 函数定义 in 单个表达式. 语法是 lambda parameters: expression. 表达式是 evaluated and returned automatically — 否 return keyword needed.
Lambdas are useful for short, throwaway functions, especially as arguments to 排序(), 映射(), 筛选(), and reduce(). They are more concise than a full def for simple operations.
Lambdas are limited to a single expression — you cannot have statements, multiple lines, or complex logic. For anything more than a simple expression, use a regular def function for readability.
示例
# Basic lambda
square = lambda x: x ** 2
print(square(5)) # 25
# As a sort key
people = [("Alice", 30), ("Bob", 25)]
people.sort(key=lambda p: p[1])
print(people) # [('Bob', 25), ('Alice', 30)]
# With map and filter
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(doubled, evens) # [2, 4, 6, 8, 10] [2, 4]Lambdas 是 单个-表达式 anonymous 函数, useful for 排序 键, 映射, and 筛选.
常见混淆
容易混淆的对象: def 函数
关键区别: lambda 是 单个-表达式 anonymous 函数. def 函数 能 有 多个 语句, docstrings, and 复杂 logic. Use lambda for 简单 one-liners; use def for 任何事 复杂.
相关术语
相关资源
相关课程
- Lambda 函数
Lambda 函数.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。