Python3 【高階函數】項目實戰:5 個學習案例
本文包含 5 個關于“高階函數”的綜合應用項目,每個項目都包含完整的程序代碼、測試案例和執行結果。具體項目是:
- 成績統計分析
- 單詞統計工具
- 簡易計算器工廠
- 任務調度器
- 數據管道處理
項目 1:成績統計分析
功能描述:
- 使用
map
和filter
對學生成績進行轉換和篩選。 - 計算平均成績并使用
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:單詞統計工具
功能描述:
- 使用
map
和filter
對文本中的單詞進行處理。 - 統計單詞長度分布。
代碼:
# 示例文本
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 + yelif operation == "subtract":return lambda x, y: x - yelif operation == "multiply":return lambda x, y: x * yelif 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 個迷你項目展示了高階函數在實際開發中的應用,通過這些項目,可以更好地理解高階函數的作用和優勢。