Python的map、filter、reduce函数
map函数func作用于给定序列的每个元素,并用一个列表来提供返回值。
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_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。
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函数,func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),
连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。
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 #coding:utf-8 2 def map_func(lis): 3 return lis + 1 4 def filter_func(li): 5 if li % 2 == 0: 6 return True 7 else: 8 return False 9 10 def reduce_func(li, lis): 11 return li + lis 12 13 li = [1,2,3,4,5] 14 map_l = map(map_func, li) #将li中所有的数都+1 15 filter_l = filter(filter_func, li) #得到li中能被2整除的 16 reduce_l = reduce(reduce_func, li) #1+2+3+4+5 17 18 print map_l #[2, 3, 4, 5, 6] 19 print filter_l #[2, 4] 20 print reduce_l #15