Python学习(20):Python函数(4):关于函数式编程的内建函数

转自 http://www.cnblogs.com/BeginMan/p/3178103.html

 

一、关于函数式编程的内建函数

 

apply()逐渐被舍弃,这里不讨论

1、filter()

#filter(func,seq)
"""纯Python描述filter函数"""
def Myfilter(bool_func,seq):
    filtered_seq = []
    for obj in seq:
        if bool_func(obj):
            filtered_seq.append(obj)
    return filtered_seq

print Myfilter(lambda x:x%3==0, [1,2,3,4,5,6,7,8,9])    #[3, 6, 9]

"""Build-In function filter()"""
print filter(lambda x:x%3==0, [1,2,3,4,5,6,7,8,9])      #[3, 6, 9]

"""非函数下的实现"""
print [x for x in [1,2,3,4,5,6,7,8,9] if x%3==0]        #[3, 6, 9]

#还记得上一节写的,如果能有for..in..if(或列表解析)能处理的最好用这个而放弃lambda

试验:列表解析和lambda性能比较

lambda:

import time
start = time.clock()
filter(lambda x:x%3==0, [i for i in range(10000000)])
end = time.clock()
print end-start     #耗时4.9441799282

列表解析:

import time
start = time.clock()
[x for x in range(10000000) if x%3==0]
end = time.clock()
print end-start     #耗时2.95589058109

从上可见,最好使用列表解析。

2、map()

"""纯Python模拟map()"""
def Mymap(func,seq):
    mapped_seq = []
    for obj in seq:
        mapped_seq.append(func(obj))
    return mapped_seq

print Mymap(lambda x:x*10,[i for i in range(10)])   #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

"""内建map()函数"""
print map(lambda x:x*10,[i for i in range(10)])     #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

"""非函数式编程"""
print [x*10 for x in range(10)]                     #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

"""多个序列的map()"""
print map(lambda x,y:x+y,[1,2,3],[4,5,6])           #[5, 7, 9]

"""None与map()"""
print map(None,[1,2,3],[4,5,6])                     #[(1, 4), (2, 5), (3, 6)]

"""None在map()中使用效果同zip(),将不相干的序列归并在一起"""
print zip([1,2,3],[4,5,6])                          #[(1, 4), (2, 5), (3, 6)]

3、reduce()

"""纯Python模拟reduce()"""
def Myreduce(bin_func,seq,init=None):
    Iseq = list(seq)
    if init is None:
        res = Iseq.pop()
    else:
        res = init
    for obj in Iseq:
        res = bin_func(res,obj)
    return res

print Myreduce(lambda x,y:x+y, [i for i in range(10)])      #45
print Myreduce(lambda x,y:x+y, [i for i in range(10)],100)  #145

"""reduce()"""
print reduce(lambda x,y:x+y,[i for i in range(10)])         #45
print reduce(lambda x,y:x+y,[i for i in range(10)],100)     #145

综上,尽量用最简便的方式去实现。

posted @ 2017-03-29 20:22  nolonely  阅读(327)  评论(0编辑  收藏  举报