第三周 Day 1
🎯 今日目標
- 掌握 Python 中函數式編程的核心概念
- 熟悉 map()、filter()、reduce() 等高階函數
- 結合 lambda 和 列表/字典 進行數據處理練習
- 了解生成器與迭代器基礎,初步掌握惰性計算概念
🧠 函數式編程基礎
函數式編程是一種“將函數作為數據處理工具”的風格,強調表達式、不可變性和鏈式操作。
🛠 常用高階函數
1?? map(func, iterable):將函數應用于序列的每個元素
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # 輸出 [1, 4, 9, 16]
2?? filter(func, iterable):過濾序列中符合條件的元素
nums = [5, 8, 12, 3, 7]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # 輸出 [8, 12]
reduce(func, iterable):連續兩兩執行函數(需導入)
from functools import reducenums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # 輸出 10
🔁 生成器 Generator
生成器是一種惰性迭代器,只在需要時計算結果,節省內存。
def countdown(n):while n > 0:yield nn -= 1for i in countdown(5):print(i)
🔄 迭代器 Iterator
任何實現了 iter() 和 next() 方法的對象都可以被稱為迭代器。
lst = iter([1, 2, 3])
print(next(lst)) # 輸出 1
print(next(lst)) # 輸出 2
🧪 今日練習任務
? 練習1:用 map 和 lambda 對列表每個數平方
nums = [2, 4, 6, 8]
result = list(map(lambda x: x**2, nums))
print(result)
? 練習2:用 filter 篩選出長度大于3的字符串
words = ['hi', 'hello', 'python', 'no']
filtered = list(filter(lambda w: len(w) > 3, words))
print(filtered)
? 練習3:實現一個生成器,生成前 N 個偶數
def even_gen(n):for i in range(n):yield i * 2print(list(even_gen(5))) # 輸出 [0, 2, 4, 6, 8]
📌 今日總結
內容 | 說明 |
---|---|
函數式編程入門 | 高階函數 map/filter/reduce |
惰性計算 | 生成器節省內存,適合大數據處理 |
迭代器基礎 | 掌握 iter() 和 next() |
實戰練習 | 提升數據處理與簡潔表達能力 |