一、map函数:对序列中的元素做运算处理,得到的新序列中的元素与原序列中的元素的位置和个数一样
引言:
1、现在有一个需求,需要将一个数字列表里面的数字每个自增1
testlist = [1, 4, 6, 7, 9]
思路:
(1)、新建一个函数,参数为testlist
(2)、函数体内容为新建一个空的临时templist
(3)、使用for循环遍历出传入list的每个元素
(4)、然后元素+1
(5)、将元素拼接到临时list中
(6)、返回临时list
具体实现:
testlist = [1, 4, 6, 7, 9]
def callist(testlist):
templist = []
for item in testlist:
templist.append(item + 1)
print(templist)
return templist
callist(testlist)
2、需求变更,除了自增功能外,我还可以自减,平方,等等操作
思路:
(1)、将计算方法提取出来到一个新的函数中
(2)、将计算方法函数当做一个参数传递到函数中
具体实现:
testlist = [1, 4, 6, 7, 9]
def plus_self(x):
return x + 1
def reduce_self(x):
return x - 1
def ride_self(x):
return x ** 2
def callist(func,testlist):
templist = []
for item in testlist:
templist.append(func(item))
print(templist)
return templist
callist(reduce_self, testlist)
另一种思路:
使用匿名函数:lambda
def callist(func, testlist):
templist = []
for item in testlist:
templist.append(func(item))
print(templist)
return templist
callist(lambda x: x + 1, testlist)
map函数正文:
map(func, *iterables):参数1:lambda函数和自定义处理函数;参数2:可迭代对象
上面的callist(func, testlist)函数其实就相当于map函数,下面使用map函数再实现上述功能:
maptest = list(map(lambda x: x + 1, testlist))
可以看出,使用map函数可以精简一大部分代码,只需要自定义函数功能和一个可迭代对象就可以实现较为复杂的功能
二、filter函数:对序列中的元素做筛选处理
filter(function or None, iterable):参数1:lambda函数和自定义处理函数;参数2:可迭代对象
循环取出后面的可迭代对象中的元素,来交给前面的函数做一个逻辑判断,返回一个bool值,来确定这个元素是被保留还是被舍弃
persion_name = ["dou1_mvp", "dou2", "dou3_mvp", "dou4_mvp"]
persionlist = list(filter(lambda n: not n.endswith("mvp"), persion_name))
print("使用filter得到的结果是:", persionlist)
三、reduce函数:将序列做加工处理,比如打包,压缩
使用前需要先导入模块:
from functools import reduce
reduce(function, sequence, initial=None):参数1,计算处理函数;参数2,序列;参数3,默认初始值
num_list = [1, 4, 6, 100]
res = reduce(lambda x, y: x + y, num_list, 5)
print("使用reduce函数得到的结果是:", res)