Python函數式編程 map reduce filter

來源:互聯網
上載者:User

標籤:hid   for   代碼   函數   tool   arguments   class   erro   編程   

 

函數式編程,使代碼簡潔高效。

 

Map函數:

  map(func, *iterables),作用是將一個列表映射到另一個列表。

class map(object):    """    map(func, *iterables) --> map object        Make an iterator that computes the function using arguments from    each of the iterables.  Stops when the shortest iterable is exhausted.    """
View Code

 

使用方法:

def f(x):    return x**2li = range(1,10)res = map(f,li)print(res)print(list(res))"""<map object at 0x000000000117E2E8>[1, 4, 9, 16, 25, 36, 49, 64, 81]"""

       

 

map(functioniterable...)

map()函數接收兩個參數,一個是函數,一個是可迭代的對象,map將傳入的函數依次作用到序列的每個元素,返回一個map對象,不是list。

 

基本等價於 [f(x) for x in interable],列表推導比map效率要高一些

map(lambda x: x+1, range(1, 3)) => [x+1 for x in range(1,3)]

 

str = ["far","foo","bar"]mp = map(lambda x:x.upper(),str)res = list(mp)print(res)"""[‘FAR‘, ‘FOO‘, ‘BAR‘]"""
View Code

 

 

Reduce函數

  reduce(function, sequence[, initial]),對可迭代對象依次做累計操作,如依次相加或相乘。

  reduce()方法接收一個函數作為累加器(accumulator),數組中的每個值(從左至右)開始合并,最終為一個值。

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__    """    reduce(function, sequence[, initial]) -> value        Apply a function of two arguments cumulatively to the items of a sequence,    from left to right, so as to reduce the sequence to a single value.    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items    of the sequence in the calculation, and serves as a default when the    sequence is empty.    """
View Code

 

直接使用會報錯

reduce(lambda x, y : x + y, [1, 3, 5, 7, 9])
"""
NameError: name ‘reduce‘ is not defined
"""

正確的使用是:reduce是functools中的一個函數,需要引用:from functools import reduce

 

使用方法:

from functools import reduceres1 = reduce(lambda x, y: x*y, [1, 2, 3])res2 = reduce(lambda x, y : x + y, [1, 3, 5])print(res1)print(res2)"""69"""

 

 

Filter函數

  filter(function or None, iterable),作用是按照所定義的函數過濾掉列表中的一些元素

class filter(object):    """    filter(function or None, iterable) --> filter object        Return an iterator yielding those items of iterable for which function(item)    is true. If function is None, return the items that are true.    """
View Code

 

使用方法:

flt = filter(lambda x: x > 5, range(10))res = list(flt)print(flt)print(res)"""<filter object at 0x0000000000649A58>[6, 7, 8, 9]"""

 

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.