[toc]
map
其中朽基,function 參數(shù)表示要傳入一個函數(shù)适秩,其可以是內(nèi)置函數(shù)巍佑、自定義函數(shù)或者 lambda 匿名函數(shù);iterable 表示一個或多個可迭代對象孔飒,可以是列表灌闺、字符串等艰争。
map() 函數(shù)的功能是對可迭代對象中的每個元素,都調用指定的函數(shù)桂对,并返回一個 map 對象园细。
listDemo = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, listDemo)
print(list(new_list))
filter
filter() 函數(shù)的功能是對 iterable 中的每個元素,都使用 function 函數(shù)判斷接校,并返回 True 或者 False猛频,最后將返回 True 的元素組成一個新的可遍歷的集合。
listDemo = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, listDemo)
print(list(new_list))
reduce
reduce() 函數(shù)通常用來對一個集合做一些累積操作蛛勉,其基本語法格式為:
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) # 元素個數(shù)與最短的列表一致
[(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)]