零基础学python-18.10 函数式编程工具:filter和reduce
这一章节我们来讨论一下函数式编程工具:filter和reduce1.filter
filter主要用于过滤序列的某些对象
>>> def test(x):
if x>0:
return x
>>> list(filter(test,range(-5,5)))
>>>
上面是filter联合def函数,过滤列表小于0的对象 我们使用lambda表达式改进上面的代码
>>> list(filter(lambda x:x>0,range(-5,5)))
>>>
由于filter跟map类似都是返回一个可迭代对象,因此都需要通过list来显示 我们下面尝试模拟filter的实现:
>>> def test(aList):
res=[]
for item in aList:
if item > 0:
res.append(item)
return res
>>> test(range(-5,5))
>>>
由于filter是内建函数,因此速度比上面的for要来得快
2.reduce
reduce主要用于对每对对象进行运算,直到最后结果,在python3.x里面reduce已经被放到functools模块里面去
>>> from functools import reduce
>>> reduce((lambda x ,y : x+y),)
10
>>> reduce((lambda x ,y : x*y),)
24
>>> reduce((lambda x ,y : x/y),)
0.041666666666666664
>>>
我们下面模拟上面reduce的实现,使得大家有一个更加直观的理解
>>> aList=
>>> def add(aList):
if not aList:
return 0
else:
return aList+test(aList)
>>> test(aList)
10
>>> def muti(aList):
if not aList:
return 0
else:
return aList*test(aList)
>>> test(aList)
10
>>>
大家是不是觉得上面很熟悉,其实在递归的时候我们就已经详细说明了上面的函数,有兴趣的可以返回去看看递归这一章节。 reduce其实就是对序列里面每对对象进行操作,然后返回操作的结果,形成新的对象,知道对象只剩下一个,形成最后的结果。
总结,这一章节我们简单介绍了filter和reduce,并且模拟了这两个内建函数的大部分实现。
这一章节就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录
版权声明:本文为博主原创文章,未经博主允许不得转载。
页:
[1]