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 根据 ‘:’ 切分,过滤空字符串 并返回列表。

  

原文地址:https://www.cnblogs.com/leeeee/p/7276074.html