Python函数式编程lambda、map与filter的实战应用
```python
# Python函数式编程:lambda、map与filter实战应用
# 1. lambda匿名函数的应用
# 基本语法:lambda 参数: 表达式
square = lambda x: x 2
add = lambda x, y: x + y
# 在排序中的应用
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
# 2. map函数的应用
# 基本语法:map(函数, 可迭代对象)
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x2, numbers))
# 处理多个可迭代对象
names = ['alice', 'bob', 'charlie']
ages = [25, 30, 35]
person_info = list(map(lambda name, age: f{name.title()} is {age} years old, names, ages))
# 3. filter函数的应用
# 基本语法:filter(函数, 可迭代对象)
numbers = range(1, 11)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# 过滤字符串列表
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
long_words = list(filter(lambda word: len(word) > 5, words))
# 4. 组合使用示例
# 数据处理管道
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 筛选偶数并计算平方
result = list(map(
lambda x: x2,
filter(lambda x: x % 2 == 0, data)
))
# 5. 实际应用场景
# 数据清洗
raw_data = [' hello ', ' WORLD ', ' python ']
cleaned_data = list(map(lambda s: s.strip().lower(), raw_data))
# 成绩处理
scores = [85, 92, 78, 60, 45, 88, 95]
passed_scores = list(filter(lambda score: score >= 60, scores))
adjusted_scores = list(map(lambda score: score + 5 if score < 90 else score, scores))
# 6. 性能考虑与最佳实践
# 使用生成器表达式替代map+filter
numbers = range(1000)
# 传统方式
result1 = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)))
# 生成器表达式(更高效)
result2 = [x2 for x in numbers if x % 2 == 0]
# 7. 实用技巧
# 在字典排序中的应用
inventory = {'apple': 10, 'banana': 5, 'orange': 8, 'grape': 3}
sorted_inventory = dict(sorted(inventory.items(), key=lambda item: item[1], reverse=True))
# 多条件排序
products = [
{'name': 'laptop', 'price': 1000, 'rating': 4.5},
{'name': 'phone', 'price': 500, 'rating': 4.2},
{'name': 'tablet', 'price': 300, 'rating': 4.7}
]
sorted_products = sorted(products, key=lambda x: (-x['rating'], x['price']))
# 8. 错误处理与边界情况
# 处理可能的异常
def safe_operation(func, data):
try:
return list(map(func, data))
except Exception as e:
print(fError: {e})
return []
# 使用示例
numbers = [1, 2, '3', 4]
safe_squared = safe_operation(lambda x: x2, numbers)
print(函数式编程实战应用示例完成!)
```
更多推荐
所有评论(0)