Python的map,reduce,filter函數

來源:互聯網
上載者:User

標籤:tle   函數   準備   第一個   平方根   href   return   資料   過濾   

#資料準備List1=range(10)list(List1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

map函數可以操作可迭代對象,輸出也是可迭代的對象
def f_map(x):    return x**2#使用map函數List2=map(f_map,List1)list(List2) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#使用lambda運算式實現mapList3=map(lambda x:x**2,List1)list(List3) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

reduce函數可以操作一組可迭代的對象,得到一個數值
from functools import reduce
def f_reduce1(x,y):    return x+ydef f_reduce2(x,y):    return x*10+ y#把一組list變成十進位的數#使用reduce函數List4=reduce(f_reduce1,List1)print(List4)List5=reduce(f_reduce2,List1)print(List5) 45 123456789#使用lambda運算式實現reduceList6=reduce(lambda x,y:x+y,List1)print(List6)List7=reduce(lambda x,y:x*10+y,List1)print(List7) 45 123456789
filter函數#第一個例子,過濾出奇數def is_odd(x):    return x%2==1List8=filter(is_odd,List1)print(list(List8))#第二個例子:過濾出平方根是整數的數import mathdef is_squr(x):    return math.sqrt(x)%1==0List9=filter(is_squr,range(1,101))print(list(List9))#使用lambda運算式實現了filterList10=filter(lambda x:math.sqrt(x)%1==0,range(1,101))print(list(List10)) [1, 3, 5, 7, 9] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


來自為知筆記(Wiz)

Python的map,reduce,filter函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.