reduce用法python_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])

输出 6

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

输出 15

reduce(lambda x,y: x+y, [1, 2, 3], 7)

输出 13

*functool标准库还有很多功能,可以参考网上的资料

python中filter,reduce,map的用法

filter的用法: 操作表list的内嵌函数'filter' 需要一个函数与一个list它用这个函数来决定哪个项应该被放入过滤结果队列中遍历list中的每一个值,输入到这个函数中如果这个函数返回Tr ...

Python内建函数reduce()用法

reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,下面讲述Python内建函数reduce()用法. ...

python基础——map/reduce

python基础——map/reduce Python内建了map()和reduce()函数. 如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Pro ...

Python Lambda 的简单用法

下面代码简单举例介绍以下 lambda的用法. from functools import reduce #1 python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而de ...

细说Python的lambda函数用法,建议收藏

细说Python的lambda函数用法,建议收藏 在Python中有两种函数,一种是def定义的函数,另一种是lambda函数,也就是大家常说的匿名函数.今天我就和大家聊聊lambda函数,在Pyth ...

函数fold 或reduce用法

http://yi-programmer.com/2011-02-24_fold.html http://c2.com/cgi/wiki?FoldFunction http://rwh.readthe ...

python中filter(),reduce()函数

filter()函数 是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 和一个list,这个函数的作用是对每个元素进行判断,返回 True或 False,filter() ...

Python之利用reduce函数求序列的最值及排序

在一般将Python的reduce函数的例子中,通常都是拿列表求和来作为例子.那么,是否还有其他例子呢?   本次分享将讲述如何利用Python中的reduce函数对序列求最值以及排序.   我们用r ...

Python中functools模块函数解析

Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数.换言之,就是能使用该模块对可调用对象进行处理. functools模块函数概览 functool ...

随机推荐

Windows phone重写返回键

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) {//需要设置这个属性 e.Cancel ...

php继承多态

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值