匿名函数
概念
匿名就是没有名字 def func(x,y,z=1): return x+y+z 匿名 lambda x,y,z=1:x+y+z #与函数有相同的作用域,但是匿名意味着引用计数为0,使用一次就释放,除非让其有名字 func=lambda x,y,z=1:x+y+z func(1,2,3) #让其有名字就没有意义 #有名函数与匿名函数的对比 有名函数:循环使用,保存了名字,通过名字就可以重复引用函数功能 匿名函数:一次性使用,随时随时定义 应用:max,min,sorted,map,reduce,filter
与内置函数的结合使用
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } # salaries=sorted(salaries) # 默认按照字典的键排序 # print(salaries) # salaries=sorted(salaries,key=lambda x:salaries[x]) #默认是升序排 # salaries=sorted(salaries,key=lambda x:salaries[x],reverse=True) #降序 # print(salaries) # lambda与map,reduce,filter # nums=[1,2,3,4,5] # res=map(lambda x:x**2,nums) # print(list(res)) # names=['alex','wupeiqi','yuanhao'] # res=map(lambda x:x+'_SB',names) # print(list(res)) # names=['alex','wupeiqi','yuanhao','egon'] # res=map(lambda x:x+'_NB' if x == 'egon' else x + '_SB',names) # print(list(res)) from functools import reduce # res=reduce(lambda x,y:x+y,range(1,101),100) # res=reduce(lambda x,y:x+y,range(1,101)) # print(res) # l=['my','name','is','alex','alex','is','sb'] # res=reduce(lambda x,y:x+' '+y+' ',l) # print(res) #filter # names=['alex_sb','wxx_sb','yxx_sb','egon'] # res=filter(lambda x:True if x.endswith('sb') else False,names) # res=filter(lambda x:x.endswith('sb'),names) # print(list(res)) # ages=[18,19,10,23,99,30] # res=filter(lambda n:n >= 30,ages) # print(list(res))
相关推荐
meylovezn 2020-09-21
wklken的笔记 2020-01-30
sulindong0 2020-01-19
chinademon 2020-01-12
JasonYeung 2019-12-28
wyqwilliam 2019-11-05
bush 2019-05-18
PythonGCS 2019-04-19
usepython 2020-05-28
举 2020-05-20
amazingbo 2020-02-26
牵手白首 2020-02-01
wyqwilliam 2020-01-02
Yellowpython 2020-01-08
xiaoge00 2019-12-21
NameCHC 2019-12-05
xcguoyu 2019-11-12