```python

# Python函数式编程:利用lambda和map提升代码简洁性

# 传统循环方式示例

numbers = [1, 2, 3, 4, 5]

squared_numbers = []

for num in numbers:

squared_numbers.append(num 2)

# 使用lambda和map的简洁实现

squared_numbers = list(map(lambda x: x2, numbers))

# 处理字符串列表

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

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

# 多列表操作

prices = [100, 200, 300]

discounts = [0.1, 0.2, 0.15]

final_prices = list(map(lambda p, d: p (1 - d), prices, discounts))

# 条件过滤与转换混合操作

mixed_data = [1, 'hello', 3.14, 'world', 42]

filtered_numbers = list(map(lambda x: x2 if isinstance(x, (int, float)) else x.upper(), mixed_data))

# 嵌套数据结构处理

students = [

{'name': 'Alice', 'scores': [85, 92, 78]},

{'name': 'Bob', 'scores': [76, 88, 95]},

{'name': 'Charlie', 'scores': [90, 85, 92]}

]

average_scores = list(map(

lambda student: {

'name': student['name'],

'avg_score': sum(student['scores']) / len(student['scores'])

}, students

))

# 与filter结合使用

numbers = range(1, 11)

even_squares = list(map(

lambda x: x2,

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

))

# 实际应用:数据清洗

raw_data = [' $100 ', ' 200$ ', '$ 300 ', '400 $ ']

cleaned_data = list(map(

lambda s: float(s.replace('$', '').replace(' ', '')),

raw_data

))

# 性能对比示例

import time

def traditional_approach(data):

result = []

for item in data:

result.append(item 2 + 10)

return result

def functional_approach(data):

return list(map(lambda x: x2 + 10, data))

# 测试数据

test_data = list(range(10000))

# 性能测试

start_time = time.time()

traditional_approach(test_data)

traditional_time = time.time() - start_time

start_time = time.time()

functional_approach(test_data)

functional_time = time.time() - start_time

print(f传统方法耗时: {traditional_time:.6f}秒)

print(f函数式方法耗时: {functional_time:.6f}秒)

# 复杂数据处理示例

employees = [

{'name': 'Alice', 'hours': 40, 'rate': 25},

{'name': 'Bob', 'hours': 35, 'rate': 30},

{'name': 'Charlie', 'hours': 45, 'rate': 20}

]

# 计算工资,考虑加班(超过40小时按1.5倍计算)

payroll = list(map(

lambda emp: {

'name': emp['name'],

'salary': emp['hours'] emp['rate'] if emp['hours'] <= 40

else 40 emp['rate'] + (emp['hours'] - 40) emp['rate'] 1.5

}, employees

))

# 多步骤数据处理管道

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

processed_data = list(map(

lambda x: fResult: {x},

map(

lambda x: x 3,

filter(lambda x: x % 2 == 0, data)

)

))

# 类型转换和格式化

mixed_numbers = ['1', '2.5', '3', '4.7', '5']

formatted_numbers = list(map(

lambda x: f${float(x):.2f},

mixed_numbers

))

print(处理结果示例:)

print(f平方数: {squared_numbers})

print(f大写名字: {capitalized_names})

print(f最终价格: {final_prices})

print(f平均分数: {average_scores})

print(f格式化数字: {formatted_numbers})

```

通过上述代码示例可以看出,lambda表达式与map函数的结合使用能够显著提升Python代码的简洁性和可读性。这种函数式编程范式不仅减少了代码行数,还使得数据处理逻辑更加清晰明了。特别是在处理列表转换、数据清洗和复杂计算场景时,lambda和map的组合能够以声明式的方式表达计算意图,避免了传统循环中的临时变量和状态管理,让代码更加函数化和模块化。

Logo

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

更多推荐