简单了解python高阶函数map/reduce


Posted in Python onJune 28, 2019

高阶函数map/reduce

Python内建了map()和reduce()函数。

我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:

简单了解python高阶函数map/reduce

现在,我们用Python代码实现:

def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print list(r)

运行结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81]
Process finished with exit code 0

map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
你可能会想,不需要map()函数,写一个循环,也可以计算出结果:

L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
L.append(f(n))
print L

的确可以,但是,从上面的循环代码,能一眼看明白“把f(x)作用在list的每一个元素并把结果生成一个新的list”吗?

所以,map()作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数,比如,把这个list所有数字转为字符串:

print list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

运行结果:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
Process finished with exit code 0

只需要一行代码。

再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

比方说对一个序列求和,就可以用reduce实现:

from functools import reduce
def add(x, y):
return x + y
print reduce(add, [1, 3, 5, 7, 9])

运行结果:

25
Process finished with exit code 0

当然求和运算可以直接用Python内建函数sum(),没必要动用reduce。

但是如果要把序列[1, 3, 5, 7, 9]变换成整数13579,reduce就可以派上用场:

from functools import reduce
def fn(x, y):
return x * 10 + y
print reduce(fn, [1, 3, 5, 7, 9])

运行结果:

13579
Process finished with exit code 0

这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数:

def fn(x, y):
return x * 10 + y
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
print reduce(fn, map(char2num, '13579'))

运行结果:

13579
Process finished with exit code 0

整理成一个str2int的函数就是:

from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))

还可以用lambda函数进一步简化成:

from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))

也就是说,假设Python没有提供int()函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现2014火车票查询代码分享
Jan 10 Python
Python中endswith()函数的基本使用
Apr 07 Python
Python os模块学习笔记
Jun 21 Python
利用Python破解验证码实例详解
Dec 08 Python
python3.6+django2.0+mysql搭建网站过程详解
Jul 24 Python
python实现的爬取电影下载链接功能示例
Aug 26 Python
关于Tensorflow分布式并行策略
Feb 03 Python
linux 下selenium chrome使用详解
Apr 02 Python
详解Python3.8+PyQt5+pyqt5-tools+Pycharm配置详细教程
Nov 02 Python
python解压zip包中文乱码解决方法
Nov 27 Python
pycharm + django跨域无提示的解决方法
Dec 06 Python
python自动化八大定位元素讲解
Jul 09 Python
安装好Pycharm后如何配置Python解释器简易教程
Jun 28 #Python
关于 Python opencv 使用中的 ValueError: too many values to unpack
Jun 28 #Python
python识别图像并提取文字的实现方法
Jun 28 #Python
python3射线法判断点是否在多边形内
Jun 28 #Python
python opencv 批量改变图片的尺寸大小的方法
Jun 28 #Python
python如何实现代码检查
Jun 28 #Python
python射线法判断一个点在图形区域内外
Jun 28 #Python
You might like
php下用GD生成生成缩略图的两个选择和区别
2007/04/17 PHP
解析php类的注册与自动加载
2013/07/05 PHP
php防止CC攻击代码 php防止网页频繁刷新
2015/12/21 PHP
PHP常用字符串操作函数实例总结(trim、nl2br、addcslashes、uudecode、md5等)
2016/01/09 PHP
PHP is_array() 检测变量是否是数组的实现方法
2016/06/13 PHP
PHP实现登录搜狐广告获取广告联盟数据的方法【附demo源码】
2016/10/14 PHP
让textarea控件的滚动条怎是位与最下方
2007/04/20 Javascript
JQuery 选项卡效果(JS与HTML的分离)
2010/04/01 Javascript
js的压缩及jquery压缩探讨(提高页面加载性能/保护劳动成果)
2013/01/29 Javascript
Knockout visible绑定使用方法
2013/11/15 Javascript
JavaScript中利用各种循环进行遍历的方式总结
2015/11/10 Javascript
Jquery实现简单的轮播效果(代码管用)
2016/03/14 Javascript
关于js函数解释(包括内嵌,对象等)
2016/11/20 Javascript
VUE中使用Vue-resource完成交互
2017/07/21 Javascript
a标签调用js的方法总结
2019/09/05 Javascript
[01:20]辉夜杯背景故事宣传片《辉夜传说》
2015/12/25 DOTA
[02:11]2016国际邀请赛中国区预选赛最美TA采访现场玩家
2016/06/28 DOTA
Python中AND、OR的一个使用小技巧
2015/02/18 Python
在DigitalOcean的服务器上部署flaskblog应用
2015/12/19 Python
Python代码解决RenderView窗口not found问题
2016/08/28 Python
Python 使用requests模块发送GET和POST请求的实现代码
2016/09/21 Python
Python多线程实现同步的四种方式
2017/05/02 Python
Python numpy生成矩阵、串联矩阵代码分享
2017/12/04 Python
python使用sqlite3时游标使用方法
2018/03/13 Python
Python3 replace()函数使用方法
2018/03/19 Python
对python中Librosa的mfcc步骤详解
2019/01/09 Python
Python 给屏幕打印信息加上颜色的实现方法
2019/04/24 Python
Python何时应该使用Lambda函数
2019/07/02 Python
Notino罗马尼亚网站:购买香水和化妆品
2019/07/20 全球购物
现在输入n个数字,以逗号,分开;然后可选择升或者降序排序;按提交键就在另一页面显示按什么排序,结果为,提供reset
2012/11/09 面试题
大学生活动策划方案
2014/02/10 职场文书
化妆师职业生涯规划书
2014/02/16 职场文书
蛋糕店创业计划书范文
2014/09/21 职场文书
事业单位年度考核个人总结
2015/02/12 职场文书
2015年医德医风工作总结
2015/04/02 职场文书
python多线程方法详解
2022/01/18 Python