python函數語言程式設計

悟空發表於2020-09-23

map

其中,function 參數列示要傳入一個函式,其可以是內建函式、自定義函式或者 lambda 匿名函式;iterable 表示一個或多個可迭代物件,可以是列表、字串等。
map() 函式的功能是對可迭代物件中的每個元素,都呼叫指定的函式,並返回一個 map 物件。

listDemo = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, listDemo)
print(list(new_list))

filter

filter() 函式的功能是對 iterable 中的每個元素,都使用 function 函式判斷,並返回 True 或者 False,最後將返回 True 的元素組成一個新的可遍歷的集合。

listDemo = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, listDemo)
print(list(new_list))

reduce

reduce() 函式通常用來對一個集合做一些累積操作,其基本語法格式為:
reduce(function, iterable)

import functools
listDemo = [1, 2, 3, 4, 5]
product = functools.reduce(lambda x, y: x * y, listDemo)
print(product)

zip

>>>a = [1,2,3]
>>>b = [4,5,6]
>>>c = [4,5,6,7,8]
>>>zipped = zip(a,b) # 打包為元組的列表
[(1, 4), (2, 5), (3, 6)]
>>>zip(a,c)          # 元素個數與最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>>zip(*zipped)      # 與 zip 相反,可理解為解壓,返回二維矩陣式
[(1, 2, 3), (4, 5, 6)]

sorted

>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, key=lambda x:x[1])               # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])            # 按年齡排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

相關文章