Python函数式编程lambda、map与filter的实战应用

```python

# Python函数式编程实战:lambda、map与filter的应用

# 1. lambda匿名函数的基础应用

# 计算平方

square = lambda x: x2

print(list(map(square, [1, 2, 3, 4, 5]))) # [1, 4, 9, 16, 25]

# 条件判断

is_even = lambda x: x % 2 == 0

print(list(filter(is_even, range(10)))) # [0, 2, 4, 6, 8]

# 2. map函数的实际应用场景

# 数据清洗:将字符串列表转换为整数

str_numbers = ['1', '2', '3', '4']

int_numbers = list(map(int, str_numbers))

print(int_numbers) # [1, 2, 3, 4]

# 多参数映射计算

calculate_area = lambda length, width: length width

lengths = [5, 8, 10]

widths = [3, 6, 4]

areas = list(map(calculate_area, lengths, widths))

print(areas) # [15, 48, 40]

# 3. filter函数的筛选功能

# 筛选有效数据

data = [0, 1, '', 'hello', None, [], [1,2]]

valid_data = list(filter(None, data))

print(valid_data) # [1, 'hello', [1, 2]]

# 复杂条件筛选

numbers = [15, 23, 8, 42, 7, 31]

divisible_by_3_and_5 = list(filter(lambda x: x % 3 == 0 and x % 5 == 0, numbers))

print(divisible_by_3_and_5) # [15]

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

# 处理学生成绩数据

students = [

{'name': 'Alice', 'score': 85},

{'name': 'Bob', 'score': 92},

{'name': 'Charlie', 'score': 78},

{'name': 'David', 'score': 65}

]

# 筛选及格学生并提取姓名

passing_students = list(

map(lambda x: x['name'],

filter(lambda x: x['score'] >= 60, students)

)

)

print(passing_students) # ['Alice', 'Bob', 'Charlie', 'David']

# 5. 实际数据处理案例

# 处理价格数据,计算含税价格

prices = [100, 200, 150, 300]

tax_rate = 0.1

# 计算含税价格并四舍五入

final_prices = list(map(lambda x: round(x (1 + tax_rate), 2), prices))

print(final_prices) # [110.0, 220.0, 165.0, 330.0]

# 筛选高价商品

expensive_items = list(filter(lambda x: x > 250, final_prices))

print(expensive_items) # [330.0]

# 6. 文本处理应用

sentences = [

Python is awesome,

Functional programming is powerful,

Lambda functions are concise

]

# 提取包含特定关键词的句子

keyword = function

relevant_sentences = list(

filter(lambda s: keyword in s.lower(), sentences)

)

print(relevant_sentences) # ['Functional programming is powerful', 'Lambda functions are concise']

# 7. 性能优化技巧

# 使用生成器表达式替代map+filter组合

numbers = range(1000000)

# 传统方式

result1 = list(map(lambda x: x2, filter(lambda x: x % 2 == 0, numbers)))

# 生成器表达式(更高效)

result2 = [x2 for x in numbers if x % 2 == 0]

# 8. 错误处理实践

def safe_convert(func, sequence):

安全的函数映射,处理异常

result = []

for item in sequence:

try:

result.append(func(item))

except Exception as e:

print(fError processing {item}: {e})

result.append(None)

return result

# 测试安全转换

mixed_data = ['123', '456', 'abc', '789']

safe_numbers = safe_convert(lambda x: int(x), mixed_data)

print(safe_numbers) # [123, 456, None, 789]

# 9. 实际项目中的最佳实践

class DataProcessor:

@staticmethod

def process_data(data, mapper=None, filter_condition=None):

通用的数据处理管道

if filter_condition:

data = filter(filter_condition, data)

if mapper:

data = map(mapper, data)

return list(data)

# 使用示例

raw_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

processed = DataProcessor.process_data(

raw_data,

mapper=lambda x: x 2,

filter_condition=lambda x: x > 5

)

print(processed) # [12, 14, 16, 18, 20]

# 总结:lambda、map和filter为Python提供了强大的函数式编程能力

# 在实际开发中,合理使用这些工具可以写出更简洁、可读性更高的代码

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值