Python的map、filter、reduce函数 [转]

1. map函数func作用于给定序列的每个元素,并用一个列表来提供返回值。 map函数python实现代码:

def map(func,seq):     

  mapped_seq = []
        for eachItem in seq:         

    mapped_seq.append(func(eachItem))
        return mapped_seq

#-*-coding:utf-8-*-
def add(x,y):
    return x+y
print map(add, range(8),range(8))

2. filter函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。 filter函数python代码实现:

def filter(bool_func,seq):     

  filtered_seq = []     

  for eachItem in seq:         

    if bool_func(eachItem):
                filtered_seq.append(eachItem)     

  return filtered_seq


#-*-coding:utf-8-*- def foo(): return filter(lambda x:x>5,range(0,10)) def bar(): return [x for x in range(0,10) if x > 5] print foo() == bar()

3. reduce函数,func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。 reduct函数python代码实现:

def reduce(bin_func,seq,initial=None): 


       lseq = list(seq)     

   if initial is None:         

    res = lseq.pop(0)     

  else:         

    res = initial     

  for eachItem in lseq:         

    res = bin_func(res,eachItem)     

  return res

#-*-coding:utf-8-*-
def foo():
    return reduce(lambda x,y:x*y,range(1,5))
print foo()

http://xiaofeng1982.blog.163.com/blog/static/31572458201093102036385/

原文地址:https://www.cnblogs.com/viviancc/p/3658016.html