zoukankan      html  css  js  c++  java
  • Python一个有意思的地方:reduce、map、filter

    今天阅读了关于Python函数式编程的系列文章,地址在这里:

    http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html

    里面提到了四个内建迭代函数:reduce、map、filter、zip。其中zip是供同时迭代多个迭代器用的,这里就不讨论了。主要讨论剩下的三个。

    我发现一个有意思的事情,就是剩下的三个函数,reduce、map和filter,三者可以相互转换。例如以reduce为基础,可以实现map和filter函数如下:

    1 def _map(func, iterable):
    2     return reduce(lambda lst, x: lst.append(func(x)) or lst, iterable, [])
    3 
    4 def _filter(func, iterable):
    5     return reduce(lambda lst, x: lst.append(x) or lst if func(x) else lst, iterable, [])

    上面的or操作符是用作流程控制的, lst.append(x) or lst 会将x添加到lst中去, 然后返回lst,因为lst.append(x)会返回None。

    基于map或filter去实现其他的函数也是可以的,只不过它们都不像基于reduce实现的map和filter那样简洁。贴出实现如下:

    这个是基于map去实现reduce和filter:

     1 #map as the base
     2 
     3 def _reduce(func, iterable, init):
     4     result = init
     5     map(lambda x: result = func(result, x), iterable)
     6     return result
     7 
     8 def _filter(func, iterable):
     9     lst= []
    10     map(lambda x: lst.append(x) if func(x), iterable)
    11     return lst

    这个是基于filter去实现另外两者:

     1 #filter as the base
     2 
     3 def _reduce(func, iterable, init):
     4     result = init
     5     filter(lambda x: result = func(result, x), iterable)
     6     return result
     7 
     8 def _map(func, iterable):
     9     lst = []
    10     filter(lambda x: lst.append(func(x)), iterable)
    11     return lst

    可以发现它们大同小异,不是很有意思。

  • 相关阅读:
    3月30日
    3月29日
    3月26日
    3月24
    3月22日
    3月20日
    博弈论基础
    $burnside$引理与$pacute olya$定理
    min-max容斥
    模板
  • 原文地址:https://www.cnblogs.com/starstone/p/4809768.html
Copyright © 2011-2022 走看看