python3高阶函数:map(),reduce(),filter()的区别
生活随笔
收集整理的這篇文章主要介紹了
python3高阶函数:map(),reduce(),filter()的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載請注明出處: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]
?
轉載于:https://www.cnblogs.com/shapeL/p/9057152.html
總結
以上是生活随笔為你收集整理的python3高阶函数:map(),reduce(),filter()的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英伟达第二季度营收增长24%
- 下一篇: websocket python爬虫_p