#这段代码
def calc(n): return n**n print(calc(10))
#换成匿名函数
calc = lambda n:n**n print(calc(10))
函数名 = lambda 参数 :返回值
#参数可以有多个,用逗号隔开 #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
#返回值和正常的函数一样可以是任意数据类型
我们可以看出,匿名函数并不是真的不能有名字。 匿名函数的调用和正常的调用也没有什么分别。 就是 函数名(参数) 就可以了
# def add(x,y):return x+y # add = lambda x,y:x+y # print(add(1,2)) # print(max([1,2,3,4,-5],key=abs)) # dic={'k1':10,'k2':100,'k3':30} # # print(max(dic.values())) # # print(max(dic)) # print(max(dic,key=lambda k:dic[k])) # def func(x): # return x*x # ret = map(lambda x:x*x,[1,2,3,4,5,6,7,8]) # print(list(ret)) # def func(num): # return num>99 and num<1000 ret = filter(func,[1,4,6,823,67,23]) print(list(ret)) # def func(num): # return num>99 and num<1000 ret = filter(lambda num: num>99 and num<1000,[1,4,6,823,67,23]) print(list(ret)) def func(num): return num > 10 ret = filter(lambda num : num > 10,[1,4,6,823,67,23]) print(list(ret))
面试题:
# d = lambda p:p*2 # t = lambda p:p*3 # x = 2 # x = d(x) #4 = d(2) # x = t(x) #12 = t(4) # x = d(x) #24 = d(12) # print(x) #2.现有两元组(('a'),('b')),(('c'),('d')), # 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}] # t1 = (('a'),('b')) # t2 = (('c'),('d')) # t3 = zip(t1,t2) #[('a','c'),('b','d')] # print(list(map(lambda t:{t[0]:t[1]},[('a','c'),('b','d')]))) #3. def multipliers(): return (lambda x:i*x for i in range(4)) print([m(2) for m in multipliers()]) # i = 0 # m = lambda x:i*x # m(2) # i = 1 # m = lambda x:i*x # m(2)