【python】filter,map,reduce和lambda函数介绍
2014-07-28 09:57
926 查看
filter(function, iterable) map(function, iterable) reduce(function, sequence) filter将 function依次作用于iterable的每个元素,如果返回值为true, 保留元素,否则从iterable里面删除。function必须返回是一个bool类型的函数。 例如:
def test(x): return (x > 3) filter(test, [1, 2, 3, 4, 5]) =====> [4, 5]
map将function作用于iterable每个元素,将对应输出结果保存为一个list。function具有返回值。
例如
def add(x): return (1 + x) map(test, [1, 2, 3, 4, 5]) =====> [2, 3, 4, 5, 6]
reduce先把iterable的前两个元素调用函数 function,再以返回值和第三个参数调用,依次执行下去
def add(x,y): return x+y reduce(add, range(1, 11)) 55
lambda:这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方:
>>> g = lambda x: x * 2 >>> g(3) 6 >>> (lambda x: x * 2)(3) 6
lambda表达式返回一个函数对象
例子:
func = lambda x,y:x+y
func相当于下面这个函数
def func(x,y): return x+y
注意def是语句而lambda是表达式
下面这种情况下就只能用lambda而不能用def
[(lambda x:x*x)(x) for x in range(1,11)]
map,reduce,filter中的function都可以用lambda表达式来生成!
相关文章推荐
- [Python] 函数lambda(), filter(), map(), reduce()
- python函数lambda(), filter(), map(), reduce()
- [Python] 函数lambda(), filter(), map(), reduce()
- python中的lambda匿名函数以及针对序列的内建函数map、filter和reduce
- python几个重要的函数(lambda,filter,reduce,map,zip)
- Python中的特殊语法:filter、map、reduce、lambda介绍
- python的lambda表达式 内建函数filter map reduce
- python几个特别函数map filter reduce lambda
- Python 函数lambda(), filter(), map(), reduce()
- Python高阶函数(Map、Reduce、Filter)和lambda函数一起使用 ,三剑客
- [Python] 函数lambda(), filter(), map(), reduce()
- python常用函数之lambda、reduce、map、sorted、filter
- Python中的filter、map、reduce、lambda函数
- [Python] 函数lambda(), filter(), map(), reduce()
- Python高级特性: 函数编程 lambda, filter,map,reduce
- python几个重要的函数(lambda,filter,reduce,map,zip) 一、匿名函数lambda lambda argument1,argument2,...argumentN :e
- python3 常见函数 map、reduce、filter、lambda、sorted
- python2,3中内建函数map,reduce,filter,sorted配合lambda
- [Python] 函数lambda(), filter(), map(), reduce()
- Python中特殊函数和表达式 filter,map,reduce,lambda