一、匿名函数也叫lambda表达式

1.匿名函数的核心:一些简单的需要用函数去解决的问题,匿名函数的函数体只有一行

2.参数可以有多个,用逗号隔开

3.返回值和正常的函数一样可以是任意的数据类型

 

二、匿名函数练习

1 请把下面的函数转换成匿名函数
2 def  add(x,y)
3         return x+y
4 add()
5 
结果: 6 sum1=lambda x,y:x+y 7 print(sum1(5,8))
1 dic = {'k1':50,'k2':80,'k3':90}
2 # func= lambda k:dic[k]
3 # print(max(dic,key=func))
4 print(max(dic,key = lambda k:dic[k]))#上面两句就相当于下面一句
比两个数的大小
1 3.map方法
2 l=[1,2,3,4]
3 # def func(x):
4 #     return x*x
5 # print(list(map(func,l)))
6 
7 print(list(map(lambda x:x*x,l)))
map方法的应用
1 l=[15,24,31,14]
2 # def func(x):
3 #         return x>20
4 # print(list(filter(func,l)))
5 
6 print(list(filter(lambda x:x>20,l)))
filter函数的小应用
 1 # 方法一
 2 t1=(('a'),('b'))
 3 t2=(('c'),('d'))
 4 # print(list(zip(t1,t2)))
 5 print(list(map(lambda t:{t[0],t[1]},zip(t1,t2))))
 6 
 7 # 方法二
 8 print(list([{i,j} for i,j in zip(t1,t2)]))
 9 
10 #方法三
11 func = lambda t1,t2:[{i,j} for i,j in zip(t1,t2)]
12 ret = func(t1,t2)
13 print(ret)
5.现有两个元组(('a'),('b')),(('c'),('d')), 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

三、列表推导式

1 6.30以内所有被3整除的数
2 print(list([i for i in range(30) if i%3==0]))
30以内能被3整除的数

三、字典推倒式

例一:将一个字典的key和value对调

1 mcase = {'a': 10, 'b': 34}
2 res1 = {i:mcase[i] for i in mcase}
3 res={mcase[i]:i for i in mcase }
4 print(res1)
5 print(res)
View Code

例二:合并大小写对应的value值,将k统一成小写

1 mcase = {'a':10,'b':34,'A':7}
2 res = {i.lower():mcase.get(i.lower(),0)+mcase.get(i.upper(),0) for i in mcase}
3 print(res)
View Code

四、集合推倒式

例:计算列表中每个值的平方,自带去重功能

1 l=[5,-5,1,2,5]
2 print({i**2 for i in l})
View Code

 

posted on 2017-08-03 16:15  海燕。  阅读(1788)  评论(0编辑  收藏  举报