码迷,mamicode.com
首页 > 其他好文 > 详细

【384】reduce 归纳函数的用法

时间:2019-03-21 13:10:28      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:port   cal   function   default   class   tle   tput   too   def   

参考:Python的functools.reduce用法

python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.

reduce的用法

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.

意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

from functools import reduce
reduce(lambda x,y: x+y, [1, 2, 3])
reduce(lambda x,y: x+y, [1, 2, 3], 9)

reduce(lambda x,y: x*y, [1, 2, 3, 4])
reduce(lambda x,y: x*y, [1, 2, 3, 4], 5)

reduce(lambda x,y: x**y, [2, 3, 4])

output:
6
15
24
120
4096

 

【384】reduce 归纳函数的用法

标签:port   cal   function   default   class   tle   tput   too   def   

原文地址:https://www.cnblogs.com/alex-bn-lee/p/10570970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!