匿名函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了匿名函数相关的知识,希望对你有一定的参考价值。
#匿名函数
def cal(n):
return n*n
#匿名函数 简单的需要用函数去解决的问题 匿名函数的函数体 只有一行
#也叫lambda表达式
# cal2 = lambda n : n*n
# ret = cal2(20)
# print(ret)
# def add(x,y):return x+y
# add2 = lambda x,y : x+y
# ret = add2(1,2)
# print(ret)
dic={‘k1‘:10,‘k2‘:100,‘k3‘:30}
# print(max(dic))
# func = lambda k:dic[k]
# print(max(dic,key = func))
# print(max(dic,key = lambda k:dic[k]))
l = [1,2,3,4]
# def pow2(x):
# return x*x
# map(pow2,l)
# print(list(map(lambda x:x*x , l)))
l = [10,11,8,12]
# def func(x):
# return x>10
# print(list(filter(func,l)))
# print(list(filter(lambda x:x>10,l)))
#现有两个元组((‘a‘),(‘b‘)),((‘c‘),(‘d‘)),请使用python中匿名函数生成列表[{‘a‘:‘c‘},{‘b‘:‘d‘}]
t1 = ((‘a‘),(‘b‘))
t2 = ((‘c‘),(‘d‘))
# print(list(zip(t1,t2)))
# print(list(map(lambda t:{t[0]:t[1]} ,zip(t1,t2))))
# print([{i:j} for i,j in zip(t1,t2)]) #item = (‘a‘, ‘c‘) i,j = (‘a‘, ‘c‘)
# func = lambda t1,t2 : [{i:j} for i,j in zip(t1,t2)]
# ret = func(t1,t2)
# print(ret)
# print(len([ i+5 for i in range(100) if i % 3 == 0 ]))
# new_l = []
# for i in range(100):
# if i%3 == 0:
# new_l.append(i+5)
#
# print(len([i//2 if i%2==0 else i for i in range(100) if i % 3 == 0 ]))
#
# for i in range(100):
# if i % 3 == 0:
# if i%2 == 0:
# new_l.append(i//2)
# else:
# new_l.append(i)
print([i for i in range(30) if i%3 == 0])
print([i*i for i in range(30) if i%3 == 0])
# names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘],
# [‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]]
# print([name for lst in names for name in lst if name.count(‘e‘) >=2])
mcase = {‘a‘: 10, ‘b‘: 34}
# for i in mcase:
# print(i)
# [i for i in mcase]
# print({key:key+‘1‘ for key in mcase})
# print({key:mcase[key] for key in mcase})
# print({mcase[key]:key for key in mcase})
# mcase = {‘a‘: 10, ‘b‘: 34, ‘A‘: 7, ‘Z‘: 3}
# mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase}
# print(mcase_frequency)
# l = [-1,1,2,1]
# print({i for i in l})
# print({i*i for i in l})
print(123)
m = input(‘>>‘)
print(m)
以上是关于匿名函数的主要内容,如果未能解决你的问题,请参考以下文章
KotlinDSL 领域特定语言 ① ( apply 标准库函数分析 | 普通匿名函数 | 扩展匿名函数 | 泛型扩展匿名函数 )