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

By 水木神風 at 2017-08-08 • 0人收藏 • 2175人看过

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. [24]  


     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  



登录后方可回帖