Python【filter、map、reduce】

來源:互聯網
上載者:User

標籤:pytho   lte   init   lam   list   rom   lambda   iter   port   

filter和map和reduce

map(function,iterable...) -> list

映射,對列表中的每個值操作 返回操作後的數值組成列表

# 給列表值+1l = [1,2,3,4,5,6,7,8,9,10]print(list(map(lambda x:x+1,l)))  #  [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

filter(function,iterable...) -> list, tuple, or string

過濾,對列表中的每個值進行判斷 返回合格原列表值

# 篩選偶數l = [1,2,3,4,5,6,7,8,9,10]print(list(filter(lambda x:x%2==0,l)))  # [2, 4, 6, 8, 10]# 補充# 若用map執行判斷語句,返回的是True或者False。map將判斷語句的結果視為需求的值,而filter會將符合判斷語句的原列表成員視為需求的值print(list(map(lambda x:x%2==0,l)))  # [False, True, False, True, False, True, False, True, False, True]

reduce(function, sequence[, initial]) -> value

對sequence中的item順序迭代調用function,函數必須要有2個參數。要是有第3個參數,則表示初始值,可以繼續調用初始值,返回一個值。

依次執行,第一次取兩個可迭代對象的值,交給function操作,將結果與下一個可迭代對象的值再交給function操作,直至結束

from functools import reduceprint(reduce(lambda x,y:x+y,l,0))  # 55 相當於1+2+3+...+10

Python【filter、map、reduce】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.