python开发【lambda篇】

lambda 与 python 高级函数的配套使用

filter函数 过滤

 1 __author__ = "Tang"
 2 
 3 # filter(lambda, [])
 4 people = ['tanglaoer','chenlaosan_sb','linlaosi_sb','wanglaowu']
 5 res = filter(lambda n:not n.endswith('_sb'),people)
 6 print(list(res)) # ['tanglaoer', 'wanglaowu']
 7 
 8 # filter(lambda,())
 9 people = ('tanglaoer','chenlaosan_sb','linlaosi_sb','wanglaowu',)
10 res = filter(lambda n:not n.endswith('_sb'),people)
11 print(tuple(res)) # ('tanglaoer', 'wanglaowu')

 

map函数 遍历操作

 1 # map(lambda,str)
 2 msg = 'tanglaoer'
 3 print(list(map(lambda x:x.upper(),msg))) #['T', 'A', 'N', 'G', 'L', 'A', 'O', 'E', 'R']
 4 
 5 # map(lambda,[])
 6 msg = ['tanglaoer','chenlaosan_sb','linlaosi_sb','wanglaowu']
 7 print(list(map(lambda x:x.upper(),msg))) #['TANGLAOER', 'CHENLAOSAN_SB', 'LINLAOSI_SB', 'WANGLAOWU']
 8 
 9 # map(lambda,())
10 msg = ('tanglaoer','chenlaosan_sb','linlaosi_sb','wanglaowu',)
11 print(tuple(map(lambda x:x.upper(),msg))) #('TANGLAOER', 'CHENLAOSAN_SB', 'LINLAOSI_SB', 'WANGLAOWU')

 

reduce函数 lambda接受两个参数

1 # reduce(lambda,[])
2 from functools import reduce
3 num_list = [1,2,3,100]
4 print(reduce(lambda x,y:x+y,num_list)) #106
5 
6 #reduce(lambda,())
7 num_list = (1,2,3,100,)
8 print(reduce(lambda x,y:x+y,num_list)) #106

 

posted @ 2018-06-25 11:02  Tanglaoer  阅读(376)  评论(0)    收藏  举报