lambda 函式
lambda 語法
lambda語法lambda parameter_list : expressionlambda:關鍵字parameter_list:參數清單,可以有多個,以逗號分隔expression:運算式,只能有一行運算式
範例說明
加法
-
Code
x = lambda a : a + 10 print(x(5)) -
Output
15
乘法
-
Code
x = lambda a, b : a * b print(x(5, 6)) -
Output
30
加總
-
Code
x = lambda a, b, c : a + b + c print(x(5, 6, 2)) -
Output
13
函式:將參數乘以 2 倍
-
Code
def myfunc(n): return lambda a : a * n doubler = myfunc(2) print(doubler(11)) -
Output
22
函式:將參數乘以 3 倍
-
Code
def myfunc (n): return lambda a : a * n tripler = myfunc(3) print(tripler(11)) -
Output
33
與 filter() 方法結合
filter()描述- 用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表
filter()語法-
filter(function, iterable)function:判斷函數iterable:可迭代的 object
-
Code
def is_odd(n): return n % 2 == 1 odd = filter(is_odd, [1, 2, 3, 4, 5]) print(odd) -
Output
[1, 3, 5]
-
lambdacombined withfilter ()method-
Code
num = [1, 2, 3, 4, 5] n = [] for i in filter(lambda x : x % 2 == 1, num): n.append(i) print(n) -
Output
[1, 3, 5]
-
與 map() 方法結合
map()描述- 會根據提供的函數對指定序列做映射,第一個參數
function以參數序列中的每一個元素調用function函數,返回包含每次function函數返回值的新列表
- 會根據提供的函數對指定序列做映射,第一個參數
map()語法-
map(function, iterable, ...)function:函數iterable:一個或多個 list
-
Code
def square(x): return x ** 2 n = list(map(square, [1, 2, 3, 4, 5])) print(n) -
Output
[1, 4, 9, 16, 25]
-
lambdacombined withmap()method-
Code
num = [1, 2, 3, 4, 5] n = [] for i in map(lambda x : x ** 2, num): n.append(i) print(n) -
Output
[1, 4, 9, 16, 25]
-
與 reduce() 方法結合
reduce()描述- 會對參數序列中元素進行累積
reduce()語法reduce(function, iterable [, initializer])-
function:函數,有 2 個參數 -
iterable:可迭代的 object -
initialize:可選,初始參數
-
Python 3.x
reduce()已經被移到functools模組裡,若要使用,需引入functools模組來調用reduce()method-
Code
from functools import reduce num = [1, 2, 3, 4, 5] def add(x, y): return x + y n = reduce(add, num) print(n) -
Output
15
lambdacombined withreduce()method-
Code
from functools import reduce num = [1, 2, 3, 4, 5] n = reduce(lambda x, y : x + y, num) print(n) -
Output
15
-
與 sorted() 方法結合
sorted()描述- 對所有可迭代的 object 進行排序操作
sorted()語法-
sorted(iterable, key=None, reverse=False)iterable:可迭代的 objectkey:用來進行比較的元素,只有一個參數,具體函數的參數就是取自於可迭代 object 中,指定可迭代 object 中的一個元素來進行排序reverse:排序規則reverse=True:降序reverse=False:升序(預設)
-
Code
student_lists = [ ['john', 'A', 15], ['jane', 'B', 12], ['dave', 'B', 10], ] n = sorted(student_lists) # 以人名進行排列 print(n) -
Output
[['dave', 'B', 10], ['jane', 'B', 12], ['john', 'A', 15]]
-
lambdacombined withsorted()method-
Code
student_lists = [ ['john', 'A', 15], ['jane', 'B', 12], ['dave', 'B', 10], ] n = sorted(student_lists, key=lambda x : x[2]) # 以年齡進行排列 print(n) -
Output
[['dave', 'B', 10], ['jane', 'B', 12], ['john', 'A', 15]]
-
lambda 函式與 def 函式差異
| 定義函式名稱 | 運算式 | 結果 | |
|---|---|---|---|
| lambda | 不需要 | 只能有一行 | 自動回傳結果 |
| def | 需要 | 可以有多行 | return 回傳結果 |