filter 函数 map 函数 reduce函数 介绍

filter 遍历序列中的每一个元素,判断每个元素得到的布尔值,如果是True则留下来

初级版本
 1 movie_people = ['lining','zhaoheng','m aoxin','m_lining','m_zhaoheng']
 2 def m_show(n):
 3     return n.endswith('m')
 4 #lambda n: n.endswith('m')
 5 
 6 def filter_test(fun,array):
 7     ret = []
 8     for p in array:
 9         if not fun(p):
10             ret.append(p)
11     return ret
12 
13 
14 # res = filter_test(m_show,movie_people)
15 # print(res)
16 
17 res = filter_test(lambda n: n.endswith('m'),movie_people)
18 print(res)

高级版本 

1 #filter 函数
2 movie_people = ['lining', 'zhaoheng', 'm aoxin', 'm_lining', 'm_zhaoheng']
3 res = filter(lambda n: not  n.endswith('m'),movie_people)
4 print(list(res))
# map 为内置函数  其两个参数  fun主要为可迭代对象实现简单的功能   array为可迭代对象

初级版本 

1 num_1 = [1,2,3,4,5]    
2 def map_test(array):   
3     ret = []           
4     for i in array:    
5         ret.append(i+1)
6     return ret         
7 print(map_test(num_1)) 

初级版本2 

 1 num_1 = [1,2,3,4,5]                 
 2 def add_one(x):                     
 3     return x+1                      
 4 def reduce_one(x):                  
 5     return x-1                      
 6 
 7 def map_test(fun,array):            
 8     ret = []                        
 9     for i in array:                 
10         res = fun(i)                
11         ret.append(res)             
12     return ret                      
13 print(map_test(add_one,num_1))      
14 print(map_test(lambda x:x+1,num_1)) 

初级版本3

 1 num_1 = [1,2,3,4,5]                    
 2 def map_test(fun,array):               
 3     ret = []                           
 4     for i in array:                    
 5         res = fun(i)                   
 6         ret.append(res)                
 7     return ret                         
 8 print(map_test(lambda x:x+1,num_1))    
 9 print(map_test(lambda x:x-1,num_1))    
10 print(map_test(lambda x:x**2,num_1))   
11                                        

高级版本 

 1 res = map(lambda x:x+1,num_1)

 2 print(list(res))  

#reduce :处理一个序列,然后把序列进行合并操作
初级版本1
 
1 num_1 = [1,2,3,4,12]
2 res = 0
3 for num in num_1:
4     res+=num
5 print(res)
 

初级版本 2

 1 def reduce_test(func,array,init=100):
 2     if init is None:
 3         res = array.pop(0)
 4     else:
 5         res = init
 6     for num in array:
 7         res=func(res,num)
 8     return res
 9 
10 ret = reduce_test(lambda x,y:x*y,num_1)
11 print(ret)

高级版本 

1 from functools import reduce
2 num_1 = [1,2,3,4,12]
3 res = reduce(lambda x,y:x*y,num_1,100)
4 print(res)
 

猜你喜欢

转载自www.cnblogs.com/lyr-1122/p/8933190.html