Python3 【高阶函数】项目实战:5 个学习案例

发布于:2025-02-10 ⋅ 阅读:(24) ⋅ 点赞:(0)

Python3 【高阶函数】项目实战:5 个学习案例

本文包含 5 个关于“高阶函数”的综合应用项目,每个项目都包含完整的程序代码、测试案例和执行结果。具体项目是:

  1. 成绩统计分析
  2. 单词统计工具
  3. 简易计算器工厂
  4. 任务调度器
  5. 数据管道处理

项目 1:成绩统计分析

功能描述

  • 使用 mapfilter 对学生成绩进行转换和筛选。
  • 计算平均成绩并使用 reduce 实现。

代码:

from functools import reduce

# 学生成绩数据
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 90},
    {"name": "Charlie", "score": 78},
    {"name": "David", "score": 92},
]

# 1. 使用 map 提取所有成绩
scores = list(map(lambda x: x["score"], students))
print("所有成绩:", scores)

# 2. 使用 filter 筛选出及格的学生(假设及格线为 80)
passed_students = list(filter(lambda x: x["score"] >= 80, students))
print("及格学生:", passed_students)

# 3. 使用 reduce 计算平均成绩
average_score = reduce(lambda x, y: x + y, scores) / len(scores)
print("平均成绩:", average_score)

输出:

所有成绩: [85, 90, 78, 92]
及格学生: [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 90}, {'name': 'David', 'score': 92}]
平均成绩: 86.25

项目 2:单词统计工具

功能描述

  • 使用 mapfilter 对文本中的单词进行处理。
  • 统计单词长度分布。

代码:

# 示例文本
text = "Python is a powerful programming language. Python is easy to learn."

# 1. 使用 map 将文本拆分为单词并转换为小写
words = list(map(lambda x: x.lower(), text.split()))
print("单词列表:", words)

# 2. 使用 filter 筛选出长度大于 4 的单词
long_words = list(filter(lambda x: len(x) > 4, words))
print("长度大于 4 的单词:", long_words)

# 3. 统计单词长度分布
from collections import defaultdict
word_length_count = defaultdict(int)
for word in words:
    word_length_count[len(word)] += 1
print("单词长度分布:", dict(word_length_count))

输出:

单词列表: ['python', 'is', 'a', 'powerful', 'programming', 'language.', 'python', 'is', 'easy', 'to', 'learn.']
长度大于 4 的单词: ['python', 'powerful', 'programming', 'language.', 'python', 'learn.']
单词长度分布: {6: 3, 2: 3, 1: 1, 8: 1, 11: 1, 9: 1, 4: 1} 

项目 3:简易计算器工厂

功能描述

  • 使用高阶函数创建加减乘除的计算器函数。

代码:

# 计算器工厂函数
def create_calculator(operation):
    if operation == "add":
        return lambda x, y: x + y
    elif operation == "subtract":
        return lambda x, y: x - y
    elif operation == "multiply":
        return lambda x, y: x * y
    elif operation == "divide":
        return lambda x, y: x / y if y != 0 else "Error: Division by zero"
    else:
        return lambda x, y: "Invalid operation"

# 创建计算器
add = create_calculator("add")
subtract = create_calculator("subtract")
multiply = create_calculator("multiply")
divide = create_calculator("divide")

# 测试计算器
print("10 + 5 =", add(10, 5))
print("10 - 5 =", subtract(10, 5))
print("10 * 5 =", multiply(10, 5))
print("10 / 5 =", divide(10, 5))
print("10 / 0 =", divide(10, 0))

输出:

10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
10 / 0 = Error: Division by zero

项目 4:任务调度器

功能描述

  • 使用高阶函数实现任务调度,支持添加任务和执行任务。

代码:

# 任务调度器
class TaskScheduler:
    def __init__(self):
        self.tasks = []

    # 添加任务
    def add_task(self, task):
        self.tasks.append(task)

    # 执行所有任务
    def run_tasks(self):
        for task in self.tasks:
            task()

# 示例任务
def task1():
    print("执行任务 1")

def task2():
    print("执行任务 2")

# 创建调度器并添加任务
scheduler = TaskScheduler()
scheduler.add_task(task1)
scheduler.add_task(task2)

# 执行任务
scheduler.run_tasks()

输出:

执行任务 1
执行任务 2

项目 5:数据管道处理

功能描述

  • 使用高阶函数实现数据管道,支持链式处理数据。

代码:

# 数据管道类
class DataPipeline:
    def __init__(self, data):
        self.data = data

    # 添加处理步骤
    def add_step(self, step):
        self.data = list(map(step, self.data))
        return self

    # 获取结果
    def get_result(self):
        return self.data

# 示例数据
data = [1, 2, 3, 4, 5]

# 创建管道并添加处理步骤
pipeline = DataPipeline(data)
result = pipeline.add_step(lambda x: x * 2) \
                 .add_step(lambda x: x + 1) \
                 .get_result()

print("处理结果:", result)

输出:

处理结果: [3, 5, 7, 9, 11]

总结

以上 5 个迷你项目展示了高阶函数在实际开发中的应用,通过这些项目,可以更好地理解高阶函数的作用和优势。


网站公告

今日签到

点亮在社区的每一天
去签到