Python的map、filter、reduce函数

map函数,对seq列表的每一个元素调用func函数,形成一个新的列表,map函数返回此新的列表。
map函数python实现代码:

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

filter函数的功能相当于过滤器。调用一个返回值为bool型的函数bool_func,来遍历每个seq中的元素,返回seq中由所有符合要求元素生成的新列表。
filter函数python代码实现:

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

reduce函数,从seq列表中去两个元素传给bin_func作为参数, 计算结果作为bin_func的第一个参数,再从seq列表中取一个元素,作为bin_func的第二个参数,依次类推,直到遍历完所有seq中的元素,返回计算结果res。

--bin_func必须为二元函数。

--python3.x中已移除此函数。
reduct函数python代码实现:

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

 举例说明: 

1 def add(x, y):
2 return x + y
3 print reduce(add,[1,2,3,4])
4 >>>10

计算过程演示如下:

1 reduce(add,[1,2,3,4])
2 res = add(1,2)
3 res = add(res,3)
4 res = add (res,4)
5 return res

亲,明白了么,好像明白了。





 

posted @ 2012-04-01 13:25  Goodpy  阅读(1385)  评论(0编辑  收藏  举报