Python函数式编程掌握lambda、map与filter的高效用法
```python
# Python函数式编程:lambda、map与filter的高效用法
# 1. lambda表达式的高效应用
# lambda是一种匿名函数,适用于简单的函数操作
square = lambda x: x 2
add = lambda x, y: x + y
# 实际应用场景
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x2, numbers))
print(f平方运算: {squared_numbers})
# 2. map函数的高阶用法
# map(function, iterable) 对可迭代对象中的每个元素应用函数
def process_data(data):
return list(map(lambda x: x.upper() if isinstance(x, str) else x2, data))
sample_data = ['hello', 3, 'world', 5]
processed = process_data(sample_data)
print(f数据处理结果: {processed})
# 多参数map应用
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_result = list(map(lambda x, y: x + y, list1, list2))
print(f多列表求和: {sum_result})
# 3. filter函数的精准筛选
# filter(function, iterable) 根据函数条件过滤元素
def filter_complex_data(data):
return list(filter(lambda x: isinstance(x, int) and x > 0, data))
mixed_data = [1, -2, 'hello', 3.5, 10, 0, 'world']
filtered = filter_complex_data(mixed_data)
print(f过滤后的正整数: {filtered})
# 4. 组合使用lambda、map和filter
# 复杂数据处理管道
def data_processing_pipeline(data):
# 第一步:过滤非数字
numbers_only = filter(lambda x: isinstance(x, (int, float)), data)
# 第二步:转换处理
processed = map(lambda x: x 1.1 if x > 0 else x, numbers_only)
# 第三步:筛选最终结果
final_result = filter(lambda x: x > 0, processed)
return list(final_result)
complex_data = [10, -5, 'text', 3.14, 0, 25, 'another']
result = data_processing_pipeline(complex_data)
print(f数据处理管道结果: {result})
# 5. 实际应用:数据清洗和转换
def clean_and_transform(raw_data):
# 清理无效数据
cleaned = filter(lambda x: x is not None and x != '', raw_data)
# 数据标准化
standardized = map(lambda x: x.strip().lower() if isinstance(x, str) else x, cleaned)
return list(standardized)
raw_input = [' Hello ', '', None, 'WORLD', ' python ']
clean_result = clean_and_transform(raw_input)
print(f数据清洗结果: {clean_result})
# 6. 性能优化技巧
def efficient_processing_large_dataset(dataset):
# 使用生成器表达式提高内存效率
result = map(
lambda x: x 2,
filter(
lambda x: x % 2 == 0,
dataset
)
)
return list(result)
large_data = range(1000000)
efficient_result = efficient_processing_large_dataset(large_data)
print(f大数据集处理样本: {efficient_result[:10]})
# 7. 函数式编程的最佳实践
def functional_programming_best_practices():
# 保持lambda简洁
simple_operations = list(map(lambda x: (x, x2, x3), range(5)))
# 合理使用类型注解
process_func = lambda x: str(x).zfill(3)
# 链式操作保持可读性
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pipeline_result = list(
map(
lambda x: x 10,
filter(
lambda x: x % 2 == 0,
data
)
)
)
return pipeline_result
best_practice_result = functional_programming_best_practices()
print(f最佳实践示例: {best_practice_result})
# 8. 错误处理和边界情况
def robust_functional_processing(data):
try:
# 添加异常处理
safe_process = map(
lambda x: x / 2 if isinstance(x, (int, float)) and x != 0 else 0,
filter(
lambda x: x is not None,
data
)
)
return list(safe_process)
except Exception as e:
print(f处理错误: {e})
return []
test_data = [10, 0, None, 20, 'invalid', 30]
robust_result = robust_functional_processing(test_data)
print(f健壮处理结果: {robust_result})
```
更多推荐


所有评论(0)