```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}) # [1, 4, 9, 16, 25]

# 2. map函数的高阶用法

# map将函数应用于可迭代对象的每个元素

def process_data(data):

数据处理函数示例

return data 2 + 10

# 使用map处理数据

processed_data = list(map(process_data, numbers))

print(f处理后的数据: {processed_data}) # [12, 14, 16, 18, 20]

# map与lambda结合使用

names = ['alice', 'bob', 'charlie']

capitalized_names = list(map(lambda name: name.title(), names))

print(f首字母大写: {capitalized_names}) # ['Alice', 'Bob', 'Charlie']

# 3. filter函数的精准筛选

# filter根据条件筛选可迭代对象中的元素

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(f偶数: {even_numbers}) # [2, 4]

# 复杂条件筛选

scores = [85, 92, 78, 60, 45, 95]

passing_scores = list(filter(lambda score: score >= 60, scores))

print(f及格分数: {passing_scores}) # [85, 92, 78, 60, 95]

# 4. 组合使用lambda、map和filter

# 数据处理管道

mixed_data = [1, 'a', 2, 'b', 3, 'c', 4]

# 筛选数字并计算平方

numbers_only = filter(lambda x: isinstance(x, int), mixed_data)

squared_result = map(lambda x: x2, numbers_only)

final_result = list(squared_result)

print(f筛选并平方: {final_result}) # [1, 4, 9, 16]

# 5. 实际应用场景

# 数据清洗和转换

raw_data = [' hello ', ' WORLD ', ' python ']

cleaned_data = list(map(lambda x: x.strip().lower(), raw_data))

print(f清洗后的数据: {cleaned_data}) # ['hello', 'world', 'python']

# 条件筛选和转换

employees = [

{'name': 'Alice', 'salary': 50000},

{'name': 'Bob', 'salary': 75000},

{'name': 'Charlie', 'salary': 45000}

]

# 筛选高薪员工并调整薪资

high_earners = filter(lambda emp: emp['salary'] > 50000, employees)

adjusted_salaries = map(lambda emp: {emp, 'salary': emp['salary'] 1.1}, high_earners)

result = list(adjusted_salaries)

print(f调整后的高薪员工: {result})

# 6. 性能优化技巧

# 使用生成器表达式替代map和filter(内存更友好)

large_dataset = range(1000000)

# 传统方式(占用更多内存)

# squared = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, large_dataset)))

# 优化方式(使用生成器)

squared_gen = (x2 for x in large_dataset if x % 2 == 0)

first_few = [next(squared_gen) for _ in range(5)]

print(f前几个平方数: {first_few})

# 7. 错误处理和最佳实践

def safe_divide(x, y):

安全的除法函数

try:

return x / y

except ZeroDivisionError:

return float('inf')

numbers_to_divide = [(10, 2), (5, 0), (8, 4)]

results = list(map(lambda pair: safe_divide(pair), numbers_to_divide))

print(f安全除法结果: {results}) # [5.0, inf, 2.0]

# 8. 函数式编程的优势总结

# - 代码简洁明了

# - 易于测试和维护

# - 支持并行处理

# - 减少副作用

# 实际项目中的应用示例

class DataProcessor:

数据处理类示例

@staticmethod

def process_pipeline(data):

数据处理管道

# 步骤1:数据清洗

cleaned = map(lambda x: x.strip() if isinstance(x, str) else x, data)

# 步骤2:数据筛选

filtered = filter(lambda x: x is not None and x != '', cleaned)

# 步骤3:数据转换

transformed = map(lambda x: x.upper() if isinstance(x, str) else x, filtered)

return list(transformed)

# 使用示例

sample_data = [' hello ', '', ' world ', None, ' python ']

processed = DataProcessor.process_pipeline(sample_data)

print(f管道处理结果: {processed}) # ['HELLO', 'WORLD', 'PYTHON']

```

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐