Python 的 Map, Filter, Reduce 三劍客函數使用教學.
Python 函式三劍客 Map, Filter, and Reduce
Map 函式
Note
map 函數能夠快速的將「list 的全部內容」透過自訂的 function 完成想要的結果
1
2
3
4
5
6
7
8
9
10
11
|
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 自定義乘 10 函數
def mcl(x):
return x * 10
# map 函式 第一引數為自定義(mcl)函式 , 第二引數為陣列 list ,並會產生一個 iterator
ans = list(map(mcl, items))
print(ans)
# [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|
匿名函數更簡潔寫法
1
2
3
4
5
6
7
|
items = [i for i in range(1,11)]
# 將 items 內的元素全部乘 10
ans = list(map(lambda x: x*10, items))
print(ans)
# [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|
Fifter 函式
Note
fifter 函數能夠快速的將「list 的全部內容」透過自訂的 function 完成指定篩選結果
1
2
3
4
5
6
7
8
9
10
11
|
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 自定義回傳大於 5 以上元素函式
def fifter_5(x):
return x > 5
# filter 函式 第一引數為自定義(fifter_5)函式 , 第二引數為陣列 list ,並會產生一個 iterator
ans = list(filter(fifter_5, items))
print(ans)
# [6, 7, 8, 9, 10]
|
匿名函數更簡潔寫法
1
2
3
4
5
6
7
|
items = [i for i in range(1,11)]
# 篩選大於 5 以上元素
ans = list(filter(lambda x: x>5, items))
print(ans)
# [6, 7, 8, 9, 10]
|
Reduce 函式
Note
reduce 函數能夠快速的將「list 的全部內容」透過自訂的 function 完成元素合併
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 載入 reduce 套件
from functools import reduce
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 自定義相加函數
def reduce_add(x, y):
return x + y
# map 函式 第一引數為自定義reduce_add函式 , 第二引數為陣列 list ,回傳將所有結果合併
ans = reduce(reduce_add, items)
print(ans)
# 55
|
匿名函數更簡潔寫法
1
2
3
4
5
6
7
8
9
10
|
# 載入 reduce 套件
from functools import reduce
items = [i for i in range(1,11)]
# 將所有元素相加整合併
ans = reduce(lambda x,y: x+y, items)
print(ans)
# 55
|