```python
# Python函数式编程实战:lambda、map、filter与reduce的深度应用
# 1. lambda匿名函数的实战应用
# 场景:快速定义简单函数
square = lambda x: x2
add = lambda x, y: x + y
# 示例:在排序中使用lambda
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
# 2. map函数的实战应用
# 场景:批量处理数据转换
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x2, numbers))
# 示例:多序列映射
names = ['alice', 'bob', 'charlie']
ages = [25, 30, 35]
user_info = list(map(lambda name, age: f{name.title()} is {age} years old, names, ages))
# 3. filter函数的实战应用
# 场景:数据筛选
numbers = range(1, 11)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# 示例:复杂条件筛选
products = [
{'name': 'laptop', 'price': 1200, 'category': 'electronics'},
{'name': 'book', 'price': 15, 'category': 'education'},
{'name': 'phone', 'price': 800, 'category': 'electronics'}
]
expensive_electronics = list(filter(
lambda product: product['price'] > 500 and product['category'] == 'electronics',
products
))
# 4. reduce函数的实战应用
from functools import reduce
# 场景:累积计算
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x y, numbers)
# 示例:复杂数据聚合
sales = [100, 200, 150, 300, 250]
total_sales = reduce(lambda acc, sale: acc + sale, sales, 0)
# 5. 组合使用实战案例
# 场景:数据处理管道
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 筛选偶数 -> 平方 -> 求和
result = reduce(
lambda acc, x: acc + x,
map(
lambda x: x2,
filter(lambda x: x % 2 == 0, data)
),
0
)
# 6. 实际项目应用:文本处理
texts = ['hello world', 'python programming', 'functional programming']
# 统计所有文本中单词的总数
total_words = reduce(
lambda acc, text: acc + len(text.split()),
texts,
0
)
# 7. 实际项目应用:数据分析
sales_data = [
{'month': 'Jan', 'revenue': 10000},
{'month': 'Feb', 'revenue': 12000},
{'month': 'Mar', 'revenue': 8000},
{'month': 'Apr', 'revenue': 15000}
]
# 计算平均收入
total_revenue = reduce(lambda acc, data: acc + data['revenue'], sales_data, 0)
average_revenue = total_revenue / len(sales_data)
# 8. 性能优化技巧
# 使用生成器表达式与函数式编程结合
large_data = range(1000000)
# 惰性求值,节省内存
processed_data = map(lambda x: x2, filter(lambda x: x % 2 == 0, large_data))
# 9. 错误处理实践
def safe_divide(x, y):
try:
return x / y
except ZeroDivisionError:
return float('inf')
numbers = [10, 5, 2, 0, 8]
divisions = list(map(lambda x: safe_divide(100, x), numbers))
# 10. 实际业务场景:用户数据处理
users = [
{'name': 'Alice', 'age': 25, 'active': True},
{'name': 'Bob', 'age': 17, 'active': True},
{'name': 'Charlie', 'age': 30, 'active': False},
{'name': 'David', 'age': 22, 'active': True}
]
# 获取活跃成年用户的姓名列表
active_adult_users = list(
map(
lambda user: user['name'],
filter(
lambda user: user['active'] and user['age'] >= 18,
users
)
)
)
# 总结:函数式编程的优势
# - 代码简洁明了
# - 易于测试和调试
# - 支持惰性求值
# - 便于并行处理
# - 提高代码可读性
print(函数式编程实战示例执行完成!)
```

被折叠的 条评论
为什么被折叠?



