首页 > 代码库 > 使用python实现内置map,filter,reduce函数

使用python实现内置map,filter,reduce函数

map函数

# -*- coding: cp936 -*-
def myselfmap(f,*args):
    def urgymap(f,args):
        if args==[]:
            return []
        else:
            return [f(args[0])]+urgymap(f,args[1:])
    if list(args)[0]==[]:             #*args有多个参数被传递时返回tuple
        return []
    else:
        return [apply(f,urgymap(lambda x: x[0],list(args)))]+apply(myselfmap,[f]+urgymap(lambda x: x[1:],list(args)))

filter函数

def myselffilter(prediate,s):
    if(isinstance(s,list)):
        if(s==[]):
            return []
        elif(isinstance(s[0],list)):
            return [myselffilter(prediate,s[0])]+myselffilter(prediate,s[1:])
        elif(prediate(s[0])):
            return [s[0]]+myselffilter(prediate,s[1:])
        else:
            return myselffilter(prediate,s[1:])
    elif(isinstance(s,tuple)):
        if(s==()):
            return ()
        elif(isinstance(s[0],tuple)):
            return myselffilter(prediate,s[0])+myselffilter(prediate,s[1:])
        elif(prediate(s[0])):
            return s[0]+myselffilter(prediate,s[1:])
        else:
            return myselffilter(prediate,s[1:])
    else:
        if(s==""):
            return ""
        elif(prediate(s[0])):
            return s[0]+myselffilter(prediate,s[1:])
        else:
            return myselffilter(prediate,s[1:])

        
#######test##########################        
#>>> myselffilter(lambda x: x>2,(1,2,3,(4,5,6)))
#(3, (4, 5, 6))
#>>> myselffilter(lambda x: x>2,[1,2,3,[4,5,6]])
#[3, [4, 5, 6]]


reduce函数

def myselfreduce(fun,s,initial=0):
    if(s==[]):
        return initial
    if(s==()):
        return initial
    if(s==""):
        return initial
    return s[0]+myselfreduce(fun,s[1:],initial)

和内置的filter不一样,本来是可以改成一样的,但是我觉得python这种类型比较我挺不喜欢的,所以没去改:)