```python

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

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

# 计算平方

square = lambda x: x 2

print(f5的平方: {square(5)})

# 判断奇偶

is_even = lambda x: x % 2 == 0

print(f4是否为偶数: {is_even(4)})

# 字符串处理

reverse_str = lambda s: s[::-1]

print(f'hello'反转后: {reverse_str('hello')})

# 2. map函数的实际应用

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

# 将列表中的每个元素平方

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

print(f平方后的列表: {squared_numbers})

# 字符串列表处理

words = ['apple', 'banana', 'cherry']

capitalized_words = list(map(lambda word: word.upper(), words))

print(f大写后的单词: {capitalized_words})

# 多个列表同时处理

list1 = [1, 2, 3]

list2 = [4, 5, 6]

sum_list = list(map(lambda x, y: x + y, list1, list2))

print(f列表相加结果: {sum_list})

# 3. filter函数的实际应用

numbers = range(1, 11)

# 筛选偶数

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

print(f1-10中的偶数: {even_numbers})

# 筛选能被3整除的数

divisible_by_3 = list(filter(lambda x: x % 3 == 0, numbers))

print(f1-10中能被3整除的数: {divisible_by_3})

# 字符串列表筛选

words = ['python', 'java', 'c', 'javascript', 'go']

long_words = list(filter(lambda word: len(word) > 4, words))

print(f长度大于4的单词: {long_words})

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

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

# 筛选偶数并计算平方

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

print(f偶数的平方: {even_squares})

# 筛选大于5的数并加倍

doubled_large = list(map(lambda x: x 2, filter(lambda x: x > 5, data)))

print(f大于5的数加倍: {doubled_large})

# 5. 实际应用场景

# 数据处理:筛选并转换学生成绩

students = [

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

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

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

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

]

# 筛选及格的学生

passing_students = list(filter(lambda student: student['score'] >= 60, students))

print(f及格的学生: {passing_students})

# 提取学生姓名和成绩等级

def get_grade(score):

if score >= 90: return 'A'

elif score >= 80: return 'B'

elif score >= 70: return 'C'

elif score >= 60: return 'D'

else: return 'F'

student_grades = list(map(lambda student: {

'name': student['name'],

'grade': get_grade(student['score'])

}, students))

print(f学生成绩等级: {student_grades})

# 6. 文件处理应用

# 假设有一个文本文件,我们想读取并处理其中的数字

sample_data = 1,2,3,4,5,6,7,8,9,10

# 解析字符串为整数列表并筛选奇数

numbers_from_string = list(map(int, sample_data.split(',')))

odd_numbers = list(filter(lambda x: x % 2 != 0, numbers_from_string))

print(f从字符串中解析出的奇数: {odd_numbers})

# 7. 性能优化示例

import time

# 传统方法 vs 函数式方法

large_list = list(range(1000000))

# 传统循环方法

start_time = time.time()

result1 = []

for num in large_list:

if num % 2 == 0:

result1.append(num 2)

traditional_time = time.time() - start_time

# 函数式方法

start_time = time.time()

result2 = list(map(lambda x: x 2, filter(lambda x: x % 2 == 0, large_list)))

functional_time = time.time() - start_time

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

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

# 8. 复杂数据处理

# 处理嵌套数据结构

employees = [

{'name': 'John', 'skills': ['Python', 'Java'], 'experience': 3},

{'name': 'Jane', 'skills': ['JavaScript', 'React'], 'experience': 5},

{'name': 'Mike', 'skills': ['Python', 'Django'], 'experience': 2}

]

# 筛选有Python技能且经验超过2年的员工

python_experts = list(filter(

lambda emp: 'Python' in emp['skills'] and emp['experience'] > 2,

employees

))

print(fPython专家: {python_experts})

# 提取员工技能列表

all_skills = list(map(lambda emp: emp['skills'], employees))

print(f所有技能: {all_skills})

# 9. 实用工具函数

# 数据清洗:去除空值和无效数据

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

clean_data = list(filter(

lambda x: x and x.strip(), # 去除空字符串和只包含空格的字符串

raw_data

))

print(f清洗后的数据: {clean_data})

# 10. 数学运算应用

# 计算斐波那契数列

fibonacci = list(map(

lambda x: (lambda f, n: f(f, n))(

lambda fib, n: n if n <= 1 else fib(fib, n-1) + fib(fib, n-2), x

),

range(10)

))

print(f前10个斐波那契数: {fibonacci})

# 总结输出

print( === 函数式编程优势总结 ===)

print(1. 代码更简洁易读)

print(2. 避免副作用,提高代码可靠性)

print(3. 便于并行处理)

print(4. 支持惰性求值,提高性能)

```

更多推荐