```python
#!/usr/bin/env python3
"""
Lambda表达式完整示例代码
基于CSDN博客内容整理的可执行Python文件
"""
from functools import reduce
from typing import List, Tuple, Callable, Any
class LambdaExamples:
"""Lambda表达式使用示例类"""
def basic_lambda_demo(self) -> None:
"""基础lambda表达式演示"""
print("=" * 50)
print("1. 基础Lambda表达式演示")
print("=" * 50)
# 普通函数定义
def add(x: int, y: int) -> int:
return x + y
# Lambda表达式等价形式
add_lambda = lambda x, y: x + y
# 调用比较
print(f"普通函数 add(2, 3) = {add(2, 3)}")
print(f"Lambda函数 add_lambda(2, 3) = {add_lambda(2, 3)}")
print(f"直接调用 lambda表达式: {(lambda x, y: x + y)(5, 7)}")
# 更多基础示例
square = lambda x: x ** 2
is_even = lambda x: x % 2 == 0
get_length = lambda s: len(s)
print(f"平方计算: square(4) = {square(4)}")
print(f"偶数判断: is_even(7) = {is_even(7)}")
print(f"字符串长度: get_length('hello') = {get_length('hello')}")
def sorting_with_lambda(self) -> None:
"""使用lambda进行排序"""
print("\n" + "=" * 50)
print("2. Lambda在排序中的应用")
print("=" * 50)
# 基础数据
points: List[Tuple[int, int]] = [(1, 2), (3, 1), (5, 4), (2, 3), (4, 2)]
students = [
("Alice", 85),
("Bob", 92),
("Charlie", 78),
("Diana", 95)
]
print("原始数据:")
print(f"坐标点: {points}")
print(f"学生成绩: {students}")
# 按元组第二个元素排序(升序)
points_by_y = points.copy()
points_by_y.sort(key=lambda x: x[1])
print(f"\n按y坐标排序: {points_by_y}")
# 按元组第一个元素排序(升序)
points_by_x = points.copy()
points_by_x.sort(key=lambda x: x[0])
print(f"按x坐标排序: {points_by_x}")
# 按y坐标降序排序
points_by_y_desc = points.copy()
points_by_y_desc.sort(key=lambda x: x[1], reverse=True)
print(f"按y坐标降序: {points_by_y_desc}")
# 学生按成绩排序
students_by_grade = students.copy()
students_by_grade.sort(key=lambda x: x[1])
print(f"学生按成绩排序: {students_by_grade}")
# 学生按成绩降序
students_by_grade_desc = students.copy()
students_by_grade_desc.sort(key=lambda x: x[1], reverse=True)
print(f"学生按成绩降序: {students_by_grade_desc}")
def higher_order_functions(self) -> None:
"""高阶函数与lambda结合使用"""
print("\n" + "=" * 50)
print("3. 高阶函数与Lambda结合")
print("=" * 50)
numbers: List[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
words: List[str] = ["apple", "banana", "cherry", "date", "elderberry"]
print(f"原始数字列表: {numbers}")
print(f"原始单词列表: {words}")
# map函数示例
squared_numbers = list(map(lambda x: x ** 2, numbers))
word_lengths = list(map(lambda x: len(x), words))
print(f"\nmap函数结果:")
print(f"数字平方: {squared_numbers}")
print(f"单词长度: {word_lengths}")
# filter函数示例
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
long_words = list(filter(lambda x: len(x) > 5, words))
print(f"\nfilter函数结果:")
print(f"偶数: {even_numbers}")
print(f"长单词: {long_words}")
# reduce函数示例
sum_all = reduce(lambda x, y: x + y, numbers)
product_all = reduce(lambda x, y: x * y, numbers[:5]) # 前5个数的乘积
max_number = reduce(lambda x, y: x if x > y else y, numbers)
print(f"\nreduce函数结果:")
print(f"所有数字和: {sum_all}")
print(f"前5个数字乘积: {product_all}")
print(f"最大数字: {max_number}")
def custom_operations(self) -> None:
"""自定义操作与lambda"""
print("\n" + "=" * 50)
print("4. 自定义操作与Lambda")
print("=" * 50)
def apply_operation(x: int, operation: Callable[[int], int]) -> int:
"""应用操作函数"""
return operation(x)
# 使用lambda传递不同的操作
results = [
apply_operation(5, lambda x: x * 2), # 乘以2
apply_operation(5, lambda x: x + 10), # 加10
apply_operation(5, lambda x: x ** 3), # 立方
apply_operation(5, lambda x: x // 2), # 整除2
]
print("应用不同操作的结果:")
operations = ["乘以2", "加10", "立方", "整除2"]
for op, result in zip(operations, results):
print(f" 5 {op}: {result}")
# 复杂数据结构操作
data = [
{"name": "Alice", "age": 25, "score": 85},
{"name": "Bob", "age": 30, "score": 92},
{"name": "Charlie", "age": 22, "score": 78},
]
print(f"\n复杂数据结构: {data}")
# 按年龄排序
sorted_by_age = sorted(data, key=lambda x: x["age"])
print(f"按年龄排序: {sorted_by_age}")
# 按分数降序
sorted_by_score_desc = sorted(data, key=lambda x: x["score"], reverse=True)
print(f"按分数降序: {sorted_by_score_desc}")
# 提取特定字段
names = list(map(lambda x: x["name"], data))
ages = list(map(lambda x: x["age"], data))
print(f"提取姓名: {names}")
print(f"提取年龄: {ages}")
def advanced_examples(self) -> None:
"""高级lambda使用示例"""
print("\n" + "=" * 50)
print("5. 高级Lambda使用示例")
print("=" * 50)
# 多参数lambda
calculate = lambda x, y, z: (x + y) * z
print(f"多参数lambda: calculate(2, 3, 4) = {calculate(2, 3, 4)}")
# 条件表达式在lambda中
classify = lambda x: "正数" if x > 0 else ("零" if x == 0 else "负数")
print(f"条件lambda: classify(5) = {classify(5)}, classify(-3) = {classify(-3)}")
# 嵌套数据结构处理
nested_data = [
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
# 计算每个子列表的和
sums = list(map(lambda sublist: sum(sublist), nested_data))
print(f"嵌套列表各子列表和: {sums}")
# 过滤空列表
non_empty = list(filter(lambda sublist: len(sublist) > 0, nested_data))
print(f"非空子列表: {non_empty}")
# 字符串处理
strings = [" hello ", " WORLD ", " python "]
cleaned = list(map(lambda s: s.strip().lower(), strings))
print(f"字符串清理: {strings} -> {cleaned}")
def practical_use_cases(self) -> None:
"""实际应用场景"""
print("\n" + "=" * 50)
print("6. 实际应用场景")
print("=" * 50)
# 场景1: 数据处理管道
raw_data = [10, 15, 20, 25, 30, 35, 40]
# 数据处理管道: 过滤 -> 转换 -> 聚合
processed_data = reduce(
lambda x, y: x + y,
map(
lambda x: x * 2,
filter(lambda x: x > 20, raw_data)
)
)
print(f"数据处理管道:")
print(f"原始数据: {raw_data}")
print(f"处理结果: {processed_data}")
# 场景2: 配置化操作
operations = {
"add": lambda x, y: x + y,
"multiply": lambda x, y: x * y,
"power": lambda x, y: x ** y,
"concat": lambda x, y: str(x) + str(y)
}
print(f"\n配置化操作:")
for op_name, op_func in operations.items():
result = op_func(3, 4)
print(f" {op_name}(3, 4) = {result}")
# 场景3: 回调函数
def process_with_callback(data: List[int], callback: Callable[[int], int]) -> List[int]:
"""使用回调函数处理数据"""
return [callback(item) for item in data]
numbers = [1, 2, 3, 4, 5]
doubled = process_with_callback(numbers, lambda x: x * 2)
squared = process_with_callback(numbers, lambda x: x ** 2)
print(f"\n回调函数应用:")
print(f"原始数据: {numbers}")
print(f"加倍: {doubled}")
print(f"平方: {squared}")
def main():
"""主函数"""
print("Lambda表达式完整示例程序")
print("基于CSDN博客内容整理")
print("=" * 60)
examples = LambdaExamples()
# 执行所有示例
examples.basic_lambda_demo()
examples.sorting_with_lambda()
examples.higher_order_functions()
examples.custom_operations()
examples.advanced_examples()
examples.practical_use_cases()
print("\n" + "=" * 60)
print("程序执行完毕!")
print("总结: Lambda表达式适用于简单的匿名函数场景,")
print("但在复杂逻辑时建议使用普通函数定义以提高可读性。")
if __name__ == "__main__":
main()
```
这个可执行的Python文件包含了博客中提到的所有lambda表达式使用场景,并进行了扩展和优化:
## 主要特性:
1. **完整覆盖**:包含基础语法、排序应用、高阶函数结合、自定义操作等所有核心内容
2. **类型注解**:使用Python类型提示,提高代码可读性
3. **模块化设计**:按功能分类组织代码,便于理解和扩展
4. **丰富示例**:提供大量实际可运行的代码示例
5. **实用场景**:包含数据处理管道、配置化操作等实际应用
## 运行方式:
```bash
python lambda_examples.py
```
该程序将依次演示lambda表达式的各种用法,每个部分都有清晰的输出说明,可以直接运行查看效果。[ref_1]