Python函数操作——map、reduce和filter函数
Python中的map、reduce和filter是自带函数库中常用的函数操作,它们分别用于对序列中的元素进行函数映射,用累计函数计算列表元素,和过滤列表元素。
map函数:
map函数常用格式为map(function, iterable),其中function是自定义函数,iterable是迭代器,将function应用到iterable中的每个元素中,生成一个可迭代的新序列。
例1:
def square(x):
return x ** 2
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_lst = map(square, lst)
print(list(squared_lst))
输出结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
例1中square函数是自定义的函数,将输入的数x平方并返回。map函数将square应用到lst列表中的每个元素中,并返回一个新的可迭代的序列squared_lst。最后将squared_lst转化成列表输出。
例2:
lst1 = [1, 2, 3] lst2 = [4, 5, 6] sum_lst = map(lambda a, b: a + b, lst1, lst2) print(list(sum_lst))
输出结果:
[5, 7, 9]
例2中使用lambda匿名函数将lst1和lst2中对应位置的元素相加,并返回新的可迭代的序列sum_lst。最终将sum_lst转化成列表输出。
reduce函数:
reduce函数常用格式为reduce(function, iterable, [initializer]),其中function是自定义函数,用于对iterable中的元素进行累积计算。initializer是可选参数,用于在开始计算时提供一个初始值。
例3:
from functools import reduce lst = [1, 2, 3, 4, 5] sum_lst = reduce(lambda a, b: a + b, lst) print(sum_lst)
输出结果:
15
例3中,使用reduce函数将列表lst中的所有元素相加起来,并返回一个结果15。在这个例子中,并没有提供initializer参数,因此reduce从lst的 个元素开始计算。
例4:
from functools import reduce lst = [2, 4, 6, 8, 10] product = reduce(lambda a, b: a * b, lst, 1) print(product)
输出结果:
3840
例4中,使用reduce函数将列表lst的所有元素相乘起来,并返回一个结果3840。在这个例子中,提供了initializer参数为1,因此reduce从lst的 个元素开始计算,并且 次计算时,将1作为初始值传入。
filter函数:
filter函数常用格式为filter(function, iterable),其中function是自定义函数,用于过滤iterable中的元素,返回仅包含经过function认可的元素的列表。
例5:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_lst = filter(lambda x: x % 2 == 0, lst) print(list(even_lst))
输出结果:
[2, 4, 6, 8, 10]
例5中,使用lambda匿名函数过滤出lst列表中所有偶数,并返回一个新的仅包含偶数的可迭代序列even_lst。最终将even_lst转化成列表输出。
例6:
lst = [1, 2, 3, 4, 5, 6] greater_than_3 = filter(lambda x: x > 3, lst) print(list(greater_than_3))
输出结果:
[4, 5, 6]
例6中,使用lambda匿名函数过滤出lst列表中所有大于3的元素,并返回一个新的仅包含大于3的可迭代序列greater_than_3。最终将greater_than_3转化成列表输出。
综上所述,Python中的map、reduce和filter函数都是自带函数库中常用的函数操作,map函数用于对序列中的元素进行函数映射,reduce函数用于用累计函数计算列表元素,filter函数用于过滤列表元素。我们可以根据具体的需求,使用这几个函数操作来完成我们想要的操作。
