python-day18--匿名函数

一、lambda表达式

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

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

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

4.练习:

请把下面的函数转换成匿名函数
def  add(x,y)
        return x+y
add()

结果:
sum1=lambda x,y:x+y
print(sum1(5,8))
View Code
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]))#上面两句就相当于下面一句
View Code
map方法
l=[1,2,3,4]
# def func(x):
#     return x*x
# print(list(map(func,l)))

print(list(map(lambda x:x*x,l)))

map方法的应用
View Code
 l=[15,24,31,14]
 # def func(x):
 #         return x>20
 # print(list(filter(func,l)))
 
 print(list(filter(lambda x:x>20,l)))
filter
# 方法一
t1=(('a'),('b'))
t2=(('c'),('d'))
# print(list(zip(t1,t2)))
print(list(map(lambda t:{t[0],t[1]},zip(t1,t2))))

# 方法二
print(list([{i,j} for i,j in zip(t1,t2)]))

#方法三
func = lambda t1,t2:[{i,j} for i,j in zip(t1,t2)]
ret = func(t1,t2)
print(ret)

5.现有两个元组(('a'),('b')),(('c'),('d')), 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
View Code

二、列表推导式

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

三、字典推导式

一、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)
二、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)

四、集合推导式

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

 

posted @ 2017-08-08 19:01  Cool·  阅读(188)  评论(0编辑  收藏  举报