Python的map,filter,reduce函数

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

def map(func,seq):
    mapped_seq = []
    for eachItem in seq:
        mapped_seq.append(func(eachItem))
    return mapped_seq

 

 

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

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 map_func(lis):
    return lis + 1

def filter_func(li):
    if li % 2 == 0:
        return True
    else:
        return False
        
def reduce_func(li, lis):
    return li + lis
    
li = [1,2,3,4,5]

map_l = map(map_func, li) #将li中所有的数都+1
filter_l = filter(filter_func, li) #得到li中能被2整除的
reduce_l = reduce(reduce_func, li) #1+2+3+4+5

print map_l
print filter_l
print reduce_l

运行结果如下:
C:\>python test1.py
[2, 3, 4, 5, 6]
[2, 4]
15

参考:http://blog.csdn.net/prince2270/archive/2009/10/16/4681299.aspx

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

No related posts.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu