天天看點

Python内建函數之——filter,map,reduce

在講述filter,map和reduce之前,首先介紹一下匿名函數lambda。

     lambda的使用方法如下:lambda [arg1[,arg2,arg3,...,argn]] : expression

     例如:

[python]  view plain copy

  1. >>> add = lambda x,y : x + y  
  2. >>> add(1,2)  
  3. 3  

     接下來分别介紹filter,map和reduce。

1、filter(bool_func,seq):此函數的功能相當于過濾器。調用一個布爾函數bool_func來疊代周遊每個seq中的元素;傳回一個使bool_seq傳回值為true的元素的序列。

     例如:

[python]  view plain copy

  1. >>> filter(lambda x : x%2 == 0,[1,2,3,4,5])  
  2. [2, 4]  

     filter内建函數的python實作:

[c-sharp]  view plain copy

  1. >>> def filter(bool_func,seq):  
  2.     filtered_seq = []  
  3.     for eachItem in seq:  
  4.         if bool_func(eachItem):  
  5.             filtered_seq.append(eachItem)  
  6.     return filtered_seq  

2、map(func,seq1[,seq2...]):将函數func作用于給定序列的每個元素,并用一個清單來提供傳回值;如果func為None,func表現為身份函數,傳回一個含有每個序列中元素集合的n個元組的清單。

    例如:

[c-sharp]  view plain copy

  1. >>> map(lambda x : None,[1,2,3,4])  
  2. [None, None, None, None]  
  3. >>> map(lambda x : x * 2,[1,2,3,4])  
  4. [2, 4, 6, 8]  
  5. >>> map(lambda x : x * 2,[1,2,3,4,[5,6,7]])  
  6. [2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]  
  7. >>> map(lambda x : None,[1,2,3,4])  
  8. [None, None, None, None]  

     map内建函數的python實作:

[python]  view plain copy

  1. >>> def map(func,seq):  
  2.     mapped_seq = []  
  3.     for eachItem in seq:  
  4.         mapped_seq.append(func(eachItem))  
  5.     return mapped_seq  

3、reduce(func,seq[,init]):func為二進制函數,将func作用于seq序列的元素,每次攜帶一對(先前的結果以及下一個序列的元素),連續的将現有的結果和下一個值作用在獲得的随後的結果上,最後減少我們的序列為一個單一的傳回值:如果初始值init給定,第一個比較會是init和第一個序列元素而不是序列的頭兩個元素。

     例如:

[c-sharp]  view plain copy

  1. >>> reduce(lambda x,y : x + y,[1,2,3,4])  
  2. 10  
  3. >>> reduce(lambda x,y : x + y,[1,2,3,4],10)  
  4. 20  

     reduce的python實作:

[python]  view plain copy

  1. >>> def reduce(bin_func,seq,initial=None):  
  2.     lseq = list(seq)  
  3.     if initial is None:  
  4.         res = lseq.pop(0)  
  5.     else:  
  6.         res = initial  
  7.     for eachItem in lseq:  
  8.         res = bin_func(res,eachItem)  
  9.     return res