首页 > 编程知识 正文

匿名函数 python,匿名函数作为参数

时间:2023-05-05 10:28:47 阅读:223276 作者:996

匿名函数 用于简化函数定义
格式:  lambda  参数1, 参数2.. : 运算 s = lambda a, b: a + bprint(s) # s 就是函数functionresult = s(1, 2)print(result)   匿名函数作为参数 # 匿名函数作为参数def func(x, y, func): print(x, y) print(func) s = func(x, y) print(s)# 调用funcfunc(1, 2, lambda a, b: a + b)  

匿名函数与内置函数的结合使用:
'''
max()  
min()
sorted()

map(): 
reduce()
filter()  

都可以用到lambda
'''

max(iter, key=) # max()list2 = [{'a': 10, 'b': 20}, {'a': 13, 'b': 20}, {'a': 9, 'b': 20}, {'a': 29, 'b': 20}]m = max(list2, key=lambda x: x['a'])print('列表的最大值:', m)  map(func, iter)

结果是class 类,需使用list()转为list

# maplist1 = [3, 4, 6, 7, 8, 9, 9, 0, 2, 5]result = map(lambda x: x + 2, list1)print(list(result)) 加入判断条件的lambda # 加入判断条件的lambdafunc = lambda x: x if x % 2 == 0 else x + 1result = func(5)print(result)# 对列表中的奇数进行加1操作result = map(lambda x: x if x % 2 == 0 else x + 1, list1)print(list(result)) reduce(func, iter, init): 对列表中的元素进行加减乘除运算的函数 # reduce(): 对列表中的元素进行加减乘除运算的函数from functools import reducetuple1 = (3, 5, 7, 8, 9, 1)result = reduce(lambda x, y: x + y, tuple1)print(result)tuple2 = (1,2,3)result = reduce(lambda x, y: x - y, tuple2, 10)print(result)  filter(func, iter)  过滤符合条件的值

结果是class 类,需使用list()转为list

list1 = [12, 6, 8, 98, 34, 36, 2, 8, 0]result = filter(lambda x: x > 10, list1)print(list(result))  sorted(iter, key= , reverse)  进行排序 students = [ {'name': 'tom', 'age': 20}, {'name': '紧张的黄蜂', 'age': 19}, {'name': '细腻的小蝴蝶', 'age': 13}, {'name': '安静的保温杯', 'age': 21}, {'name': 'jack', 'age': 23}, {'name': 'steven', 'age': 18},]# 找出所有年龄大于20岁学生result = filter(lambda x: x['age'] > 20,students)print(list(result))# sorted(iter, key= , reverse)# 按照年龄从小到大排序students = sorted(students,key=lambda x:x['age'],reverse=True)print(students)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。