匿名函数 别称: lambda表达式
函数,没有名字
def wahaha(n):#wahaha
return n**2
print(wahaha.__name__)
qqxing = lambda n : n**2
print(qqxing.__name__)#lambda
ret = qqxing(8)
print(ret)#64
f = lambda *args:sum(args)
ret = f(1,2,3,4,5)
print(ret)#15
# 匿名函数
dic={'k1':10,'k2':100,'k3':30}
def func(k):
return dic[k]
m = max(dic,key = func)
print(m)#k2
m = max(dic,key = lambda k:dic[k])
print(m)#k2
# 内置函数+匿名函数
l1 = [1,5,7,4,8]
ret = map(lambda n : n**2%2 ,l1)
print(list(ret))#[1, 1, 1, 0, 0]
l2 = [3,10,20,50,22,7]
ret = filter(lambda n : n>20,l2)
print(list(ret))#[50, 22]
l3 = [{'name':'alex','age':83},{'name':'wusir','age':38}]
def func(dic):
return dic['age']>40
ret = filter(lambda dic:dic['age']>40,l3)
print(list(ret))#[{'name': 'alex', 'age': 83}]
#2
def func(dic):
return dic['age']
ret = sorted(l3,key=lambda dic:dic['age'])
print(ret)#[{'name': 'wusir', 'age': 38}, {'name': 'alex', 'age': 83}]
def func(dic):
dic['age'] += 1
return dic
ret = map(lambda dic : {'name':dic['name'],'age':dic['age']+1},l3)
print(list(ret))#[{'age': 84}, {'age': 39}]
手机扫一扫
移动阅读更方便
你可能感兴趣的文章