Python 进阶 - 第二十节


📋 本节要点

知识点 说明
函数式编程 函数作为一等公民
高阶函数 接收函数或返回函数
map() 对序列每个元素操作
filter() 过滤序列元素
reduce() 累计计算序列
sorted() 自定义排序规则

1. 函数式编程概述

函数式编程是一种编程范式,将计算视为函数的求值。

  • 函数是一等公民(可以赋值给变量、作为参数传递、作为返回值)
  • 高阶函数:接收函数或返回函数的函数
  • 纯函数:不依赖外部状态,不产生副作用

2. map() - 映射函数

map(func, iterable) 对序列的每个元素应用函数,返回迭代器。

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

# 计算每个数的平方
squares = map(lambda x: x ** 2, numbers)
print(list(squares))  # [1, 4, 9, 16, 25]

3. filter() - 过滤函数

filter(func, iterable) 过滤序列,返回满足条件的元素。

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

# 过滤偶数
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # [2, 4, 6, 8, 10]

4. reduce() - 累计函数

reduce(func, iterable, initial) 对序列进行累计计算。

需要 from functools import reduce

from functools import reduce

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

# 求和
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 15

# 求乘积
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

5. sorted() 自定义排序

# 基本排序
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers))              # [1, 2, 5, 8, 9]
print(sorted(numbers, reverse=True))  # [9, 8, 5, 2, 1]

# 按字符串长度排序
words = ["apple", "hi", "python", "a", "cat"]
print(sorted(words, key=len))  # ['a', 'hi', 'cat', 'apple', 'python']

6. max() / min() 自定义规则

students = [
    {"name": "张三", "score": 85},
    {"name": "李四", "score": 92}
]

# 按分数找最高
print(max(students, key=lambda x: x["score"]))  # {'name': '李四', 'score': 92}

7. 实战案例:学生成绩统计

from functools import reduce

students = [
    {"name": "张三", "score": 85},
    {"name": "李四", "score": 92},
    {"name": "王五", "score": 78}
]

# 最高分
highest = max(students, key=lambda x: x["score"])
print(f"最高分:{highest['name']} - {highest['score']}")

# 平均分
scores = list(map(lambda x: x["score"], students))
average = reduce(lambda x, y: x + y, scores) / len(students)
print(f"平均分:{average:.2f}")

运行结果:

最高分:李四 - 92
平均分:85.00

Python 进阶课程全部完成! 🎉