轉載請注明出處:https://www.cnblogs.com/shapeL/p/9057152.html
1.map():遍歷序列,對序列中每個元素進行操作,最終獲取新的序列
1 print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
輸出結果:
['1', '2', '3', '4', '5', '6', '7', '8', '9']
1 def square(x): 2 return x**2 3 result = list(map(square,[1,2,3,4,5])) 4 print(result)
輸出結果:
[1, 4, 9, 16, 25]
備注:map()執行后發現返回結果:<map object at 0x006F34F0>
因為map():Python 2.x 返回列表;Python 3.x 返回迭代器
1 def square(x): 2 return x**2 3 result = map(square,[1,2,3,4,5]) 4 print(result)
輸出結果:
<map object at 0x006F34F0>
在python3里面,map()的返回值已經不再是list,而是iterators, 所以想要使用,只用將iterator轉換成list即可, 比如list(map())
2.reduce():對於序列內所有元素進行累計操作,即是序列中后面的元素與前面的元素做累積計算(結果是所有元素共同作用的結果)
1 def square(x,y): 2 return x*y 3 result = reduce(square,range(1,5)) 4 print(result)
輸出結果:
24
3.filter():‘篩選函數’,filter()把傳人的函數依次作用於序列的每個元素,然后根據返回值是True還是false決定保留還是丟棄該元素,返回符合條件的序列
1 def func(x): 2 return x%2==0 3 print(list(filter(func,range(1,6))))
輸出結果:
[2, 4]