python内置函数中的map,filter,reduce函数例子

一: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]))

 

转载于:https://www.cnblogs.com/wangdamao/p/10439331.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值