Python 匿名函数 lambda函数 与匿名函数搭配使用函数 map zip filter reduce

匿名函数(lambda函数)

函数格式:  lambda 形参:返回值

   如: lambda x:x**2

例:

res = lambda x:x**2

res(3)  #结果为9

该函数一般不单独使用,而是用map、zip等函数配合使用:

map(fun,*iterables) 映射

把可迭代对象中的每个值当作实参,传递给函数,

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

res = list(map(lambda x:x**2,l))

 

zip(*iterables) 

拉链函数,把两(多)个可迭代对象的对应值组成一个元组

l = [11, 22, 33, 44, 55, 66, 77]
name_list = ['jason', 'kevin', 'tony', 'jerry']
l1 = [1, 2, 3, 4, 5, 6, 7]
l2 = [8, 7, 6, 4, 3, 2, 1]

res = zip(l,name_list,l1,l2)

 

filter(fun,*iterables)

把可迭代对象的每个值传递给函数,过滤掉不符合条件的值

l = [11, 22, 33, 44, 55]

res = filter(lambda x:x>25,l)

 

reduce 归总

from functools import reduce

d = [11, 22, 33, 44, 55, 66, 77, 88, 99]
res = reduce(lambda x, y: x + y, d)

结果相当于把d中的所有值相加

运行过程中,把前两个值相加的结果当作新值,再与后一个值相加

 

posted on 2021-11-27 10:49  秋不语  阅读(71)  评论(0)    收藏  举报

导航