python基础之(map, filter,reduce,lambda,global 变量)
2017-12-22 11:16
501 查看
map(square, range(5)) Out[9]: [0, 1, 4, 9, 16] filter(f, sq) 函数的作用相当于,对于 sq 的每个元素 s,返回所有 f(s) 为 True 的 s 组成的列表,相当于: [s for s in sq if f(s)] In [10]: def is_even(x): return x % 2 == 0 filter(is_even, range(5)) Out[10]: [0, 2, 4] 一起使用: In [11]: map(square, filter(is_even, range(5))) Out[11]: [0, 4, 16] reduce(f, sq) 函数接受一个二元操作函数 f(x,y),并对于序列 sq 每次合并两个元素: In [12]: def my_add(x, y): return x + y reduce(my_add, [1,2,3,4,5]) Out[12]: 15 #返回一个函数 def make_logger(target): def logger(data): with open(target, 'a') as f: f.write(data + '\n') return logger foo_logger = make_logger('foo.txt') foo_logger('Hello') foo_logger('World') !cat foo.txt Hello World In [15]: import os os.remove('foo.txt') 匿名函数 在使用 map, filter,reduce 等函数的时候,为了方便,对一些简单的函数,我们通常使用匿名函数的方式进行处理,其基本形式是: lambda <variables>: <expression> 例如,我们可以将这个: In [16]: print map(square, range(5)) [0, 1, 4, 9, 16] 用匿名函数替换为: In [17]: print map(lambda x: x * x, range(5)) [0, 1, 4, 9, 16] 匿名函数虽然写起来比较方便(省去了定义函数的烦恼),但是有时候会比较难于阅读: In [18]: s1 = reduce(lambda x, y: x+y, map(lambda x: x**2, range(1,10))) print(s1) 285 当然,更简单地,我们可以写成这样: In [19]: s2 = sum(x**2 for x in range(1, 10)) print s2 285 global 变量 一般来说,函数中是可以直接使用全局变量的值的: In [20]: x = 15 def print_x(): print x print_x() 15 但是要在函数中修改全局变量的值,需要加上 global 关键字: In [21]: x = 15 def print_newx(): global x x = 18 print x print_newx() print x 18 18 如果不加上这句 global 那么全局变量的值不会改变: In [22]: x = 15 def print_newx(): x = 18 print x print_newx() print x
相关文章推荐
- Python 第三篇(上):python文件基础操作、json模块、lambda、map、filter、reduce和函数位置参数
- Python特殊语法:filter、map、reduce、lambda [转]
- Python高阶函数:filter、map、reduce、lambda
- Python函数式编程学习:lambda, map, reduce, filter
- Python的lambda, filter, reduce 和 map简介
- python的lambda、filter、map、reduce、zip函数
- 【python】filter,map,reduce和lambda函数介绍
- Python一些特殊用法(map、reduce、filter、lambda、列表推导式等)
- Python 特殊语法filter、map、reduce、lambda
- python:filter、lambda和map、reduce
- Python基础-map/reduce/filter
- Python基础-map/reduce/filter
- Python 特殊语法:filter、map、reduce、lambda
- python 中的 filter, lambda, map, reduce 内置函数
- python中的函数:filter/map/reduce/lambda
- Python特殊语法:filter、map、reduce、lambda
- Python list--> Filter , Map , Reduce 使用笔记 (lambda )
- Python特殊语法:filter、map、reduce求和差积、lambda
- [转]Python特殊语法:filter、map、reduce、lambda
- python 的几个内置函数(lambda ,zip, filter, map, reduce )用法