Python函数式编程lambda、map与filter的巧妙应用
```python
# Python函数式编程:lambda、map与filter的巧妙应用
# 1. lambda匿名函数的灵活运用
# 创建简单的数学运算函数
add = lambda x, y: x + y
square = lambda x: x 2
is_even = lambda x: x % 2 == 0
# 在排序中的使用
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))
# 筛选特定条件的字符串
words = ['python', 'java', 'javascript', 'c++', 'go']
long_words = list(filter(lambda word: len(word) > 4, words))
# 4. 组合应用的强大威力
# 链式处理:筛选后转换
mixed_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(map(lambda x: x2, filter(lambda x: x > 5, mixed_numbers)))
# 复杂数据处理
data = [{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 78}]
# 筛选高分学生并提取姓名
high_scorers = list(map(lambda x: x['name'],
filter(lambda x: x['score'] >= 90, data)))
# 5. 实际应用场景
# 数据清洗
raw_data = [' hello ', 'WORLD', ' python ']
cleaned_data = list(map(lambda x: x.strip().lower(), raw_data))
# 条件计算
temperatures = [20, 25, 30, 15, 35]
hot_days = list(filter(lambda temp: temp > 28, temperatures))
# 6. 性能优化技巧
# 使用生成器表达式提高效率
large_dataset = range(1000000)
# 使用map和filter的组合
processed_data = map(lambda x: x2,
filter(lambda x: x % 3 == 0, large_dataset))
# 7. 函数组合的优雅实现
def compose(functions):
return lambda x: reduce(lambda acc, f: f(acc), functions, x)
# 示例:先平方,再筛选,最后转换为字符串
pipeline = compose(
lambda x: x2,
lambda x: x if x > 10 else None,
lambda x: str(x) if x else 'Too small'
)
# 应用管道
results = list(filter(None, map(pipeline, range(1, 6))))
# 总结应用要点
def demonstrate_usage():
# lambda的简洁性
quick_calc = lambda x: x 2 + 10
# map的批量处理能力
prices = [100, 200, 300]
discounted = list(map(lambda price: price 0.9, prices))
# filter的精确筛选
numbers = [15, 20, 25, 30, 35]
divisible_by_5 = list(filter(lambda x: x % 5 == 0, numbers))
return quick_calc(5), discounted, divisible_by_5
# 调用演示
demo_result = demonstrate_usage()
```
更多推荐
所有评论(0)