zoukankan      html  css  js  c++  java
  • python 中的 filter, lambda, map, reduce 内置函数

    http://blog.csdn.net/dysj4099/article/details/17412797


    1. lambda 匿名函数

     

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. >>> lambda_a = lambda a : a + 1  
    2. >>> lambda_a(2)  
    3. 3  

    构建一个函数lambda_a,不需要显示指定函数名,冒号之前是参数,此功能可以跟filter共同使用。


    2. filter(func, seq) 用func过滤seq中的每个成员,并把func返回为True的成员构成一个新的seq

     

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. >>> la = lambda a : a >= 10  

    2. >>> test = [1012152213]  
    3. >>> filter(la, test)  
    4. [10152213]  

    5. >>> test2 = ['haha'15102]  
    6. >>> filter(la, test2)  
    7. ['haha'1510]  

    8. >>> la('test')  
    9. True  
    10. >>> la('best')  
    11. True  
    12. >>> la('%')  
    13. True  

    14. >>> test3 = [[], 152]  
    15. >>> filter(la, test3)  
    16. [[], 15]  

    3.  map(fun, seq) 用func处理seq中的每个成员,并组织成新seq返回

     

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. >>> def a(x): return x**2  
    2. ...   
    3. >>> map(a, [1,2,3,4,5])  
    4. [1491625]  

    4. reduce(func, seq, init_v)  func必须为两个参数,对seq中的成员迭代调用func(return后的值参与下一次迭代),并且可以指定初始化值 init_v

     

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. >>> def add(x, y): return x + y  
    2. ...   
    3. >>> reduce(add, range(110), 15)  
    4. 60  

     

    组合用法举例:

     

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. >>> import string  
    2. >>> str_path = ". : /usr/bin:/usr/local/bin/ : usr/sbin/ :"  
    3. >>> filter(lambda path:path != '', map(lambda paths:string.strip(paths), string.split(str_path,':')))  
    4. ['.''/usr/bin''/usr/local/bin/''usr/sbin/']  


    将字符串str_path 根据 ‘:’ 切分,过滤空字符串 并返回列表。

      

  • 相关阅读:
    js数组去重五种方法
    wm_concat 多行字符串拼接
    ORACLE WITH AS 简单用法
    layui laytpl 语法
    看懂Oracle执行计划
    GIT RM -R --CACHED 去掉已经托管在GIT上的文件
    sourceTree使用教程--拉取、获取
    SourceTree忽略文件和文件夹
    layui table 详细讲解
    利用POI实现下拉框级联
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276074.html
Copyright © 2011-2022 走看看