上一期小練習解答(第7期回顧)
? 練習1:找出1~100中能被3或5整除的數
result = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]
? 練習2:生成字符串長度字典
words = ["apple", "banana", "grape"]
lengths = {word: len(word) for word in words}
? 練習3:乘法字典
multiplication_table = {(i, j): i * j for i in range(1, 6) for j in range(1, 6)}
?? 練習4:唯一偶數集合
lst = [1, 2, 2, 3, 4, 4, 6]
even_set = {x for x in lst if x % 2 == 0}
本期主題:Lambda函數與高階函數
🟦 8.1 匿名函數 lambda
匿名函數(Lambda)是用來創建簡單函數的一種簡潔方式。
? 基本語法:
lambda 參數: 表達式
?? 注意:lambda
函數只能寫一行表達式,不能有多行語句。
示例:普通函數 vs lambda
def add(x, y):return x + yadd_lambda = lambda x, y: x + yprint(add(2, 3)) # 5
print(add_lambda(2, 3)) # 5
8.2 高階函數簡介
高階函數指的是接收函數作為參數,或返回另一個函數的函數。
8.3 map() 函數
對可迭代對象中的每個元素執行某個函數。
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16]
8.4 filter() 函數
篩選符合條件的元素。
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]
?
8.5 reduce() 函數(需導入 functools)
對所有元素累積運算。
from functools import reducenums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # 10
?
應用實例:常見用法組合
🔹 對字符串列表大小寫轉換
words = ["apple", "banana", "grape"]
upper = list(map(lambda w: w.upper(), words))
🔹 保留長度大于5的字符串
long_words = list(filter(lambda w: len(w) > 5, words))
🔹 所有價格加稅10%
prices = [100, 200, 300]
taxed = list(map(lambda p: round(p * 1.1, 2), prices))
本期小練習
-
使用
map
將[1, 2, 3, 4, 5]
轉為字符串列表。 -
使用
filter
從列表中篩選出所有回文字符串(例如"madam"
)。 -
使用
reduce
計算[2, 3, 4]
的乘積。 -
定義一個
lambda
函數,實現 x2 + 2x + 1 的計算。
本期小結
-
學習了 lambda匿名函數 的用法。
-
掌握了三種常用的高階函數:map, filter, reduce。
-
初步感受了 函數式編程思想 的強大與簡潔。
第9期預告:
下一期我們將深入了解:
-
Python中的函數定義進階
-
可變參數:
*args
與**kwargs
-
參數解包與實戰技巧
-
默認參數 & 關鍵字參數的使用場景
?
?
?
?
?
?