一:map函数
def addone(x):
return x+1
def changeList(func,list):
newList=[]
for i in list:
res=func(i)
newList.append(res)
return newList
#不使用lambda函数
qq=changeList(addone,[1,2,3])
print(qq)
#使用lambda函数
print(changeList(lambda x:x+1,[1,2,3]))
#使用map函数
print(list(map(lambda x:x+1,[1,2,3])))
二:filter函数
def test(x):
return x.startswith("a")
def filter_test(func,list):
newList=[]
for i in list:
if not func(i):
newList.append(i)
return newList
#不使用lambda函数
qq=filter_test(test,["aer","dsa","fds"])
print(qq)
#使用lambda函数
print(filter_test(lambda x:x.startswith("a"),["aer","dsa","fds"]))
#使用filter函数
print(list(filter(lambda x:not x.startswith("a"),["aer","dsa","fds"])))
三:reduce函数
from functools import reduce
def multi(x,y):
return x*y
def reduce_test(func,x,init=None):
if init is None:
res=x.pop(0)
else:
res=init
for num in x:
res=func(res,num)
return res
#不适用lambda表达式
print(reduce_test(multi,[1,2,3,4,5,6]))
#使用lambda表达式
print(reduce_test(lambda x,y:x*y,[1,2,3,4,5,6]))
#reduce函数
print(reduce(lambda x,y:x*y,[1,2,3,4,5,6]))