python---------匿名函数

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

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

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

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

二、匿名函数练习

1.请把下面的函数转换成匿名函数

  1 
  2 def  add(x,y)
  3         return x+y
  4 add()
  5 
  6 结果:
  7 sum1=lambda x,y:x+y
  8 print(sum1(5,8))
请把下面的函数转换成匿名函数 View Code
2.比两个数的大小
  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

3. map方法的应用

  1 l=[1,2,3,4]
  2 # def func(x):
  3 #     return x*x
  4 # print(list(map(func,l)))
  5 
  6 print(list(map(lambda x:x*x,l)))
  7 
map方法 View Code

4.filter函数的小应用

  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)))
View Code

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

  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)
 14 
 15 5.现有两个元组(('a'),('b')),(('c'),('d')), 请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
View Code

三、列表推导式

6. 30以内能被3整除的数

  1 print(list([i for i in range(30) if i%3==0]))
View Code

三、字典推倒式

例一:将一个字典的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

 

 

归类: python相关

原文地址:https://www.cnblogs.com/lz1996/p/11572743.html