Python中reduce与lambda的结合使用
2017-08-11 23:40
567 查看
reduce是Python的内置方法,其官方解释是:
function不能为
考虑没有
考虑没有
考虑有
另外,考虑一种特殊情况,即
reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
function不能为
None。
考虑没有
initial,且function为lambda表达式的情形。此时,lambda表达式的
:左边有且须有2个参数,
:右边是关于这2个参数的表达式。
reduce(lambda x,y:x+y, [1,2,3]) #6 reduce(lambda x,y:x * y, [1,2,4]) #8 reduce(lambda x,y: x and y, [True,False,True]) #False def f(x,y): return x+y reduce(lambda x,y:f(x,y), [1,2,3]) #6
考虑没有
initial,且function不为lambda表达式的情形。
def f(x,y): return x+y reduce(f, [1,2,3]) #6
考虑有
initial,且function为lambda表达式的情形。同样,lambda表达式的
:左边有且须有2个参数,
:右边是关于这2个参数的表达式。
reduce(lambda x,y:x+y, [1,2,3], 10) #16 reduce(lambda x,y:x+y, [], 10) #10
另外,考虑一种特殊情况,即
sequence为函数列表(即列表中的每个元素均是某一个函数)的情况。
def f1(x): return x + [1] def f2(x): return x + [2] reduce(lambda x, y: y(x), [f1, f2], [0]) #[0, 1, 2]
相关文章推荐
- 【python】详解lambda匿名函数以及结合map、reduce、filter、sorted等使用
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用
- python中的zip、map、reduce 、lambda函数的使用。
- Python 中的 map, reduce, zip, filter, lambda基本使用方法
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用
- Python高阶函数(Map、Reduce、Filter)和lambda函数一起使用 ,三剑客
- Python3 zip,lambda,map,reduce的使用
- python的reduce和lambda使用
- python sorted函数(结合使用lambda和operator.itemgetter()来对字典进行排序)
- python使用reduce,lambda
- Python中filter与lambda的结合使用
- Python中map与lambda的结合使用
- Python list--> Filter , Map , Reduce 使用笔记 (lambda )
- Python中filter、lambda、map、reduce的使用
- Python特殊语法:filter、map、reduce、lambda [转]
- Python 猜价格游戏:while 结合 if学习使用(2)
- python中的reduce的使用
- Python中几个操作列表的内置函数filter(),map(),reduce(),lambda
- lambda表达式使用方法详解 分类: python 2013-03-15 10:58 396人阅读 评论(0) 收藏