简单了解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实现的远程登录windows系统功能示例
Jun 21 Python
如何用Python合并lmdb文件
Jul 02 Python
Python中Proxypool库的安装与配置
Oct 19 Python
10 分钟快速入门 Python3的教程
Jan 29 Python
python基于Selenium的web自动化框架
Jul 14 Python
Python中six模块基础用法
Dec 08 Python
使用python快速实现不同机器间文件夹共享方式
Dec 22 Python
Python对象的属性访问过程详解
Mar 05 Python
区分python中的进程与线程
Aug 13 Python
python中如何打包用户自定义模块
Sep 23 Python
谈谈python垃圾回收机制
Sep 27 Python
python语言实现贪吃蛇游戏
Nov 13 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
无法载入 mcrypt 扩展,请检查 PHP 配置终极解决方案
2011/07/18 PHP
php实现json编码的方法
2015/07/30 PHP
JavaScript中的Window窗口对象
2008/01/16 Javascript
jquery移动listbox的值原理及代码
2013/05/03 Javascript
node.js 使用ejs模板引擎时后缀换成.html
2015/04/22 Javascript
遮罩层点击按钮弹出并且具有拖动和关闭效果(两种方法)
2015/08/20 Javascript
基于jquery实现全屏滚动效果
2015/11/26 Javascript
JS实现环形进度条(从0到100%)效果
2016/07/05 Javascript
jQuery表单验证插件解析(推荐)
2016/07/21 Javascript
js显示动态时间的方法详解
2016/08/20 Javascript
angular分页指令操作
2017/01/09 Javascript
微信小程序 使用腾讯地图SDK详解及实现步骤
2017/02/28 Javascript
详解使用JS如何制作简单的ASCII图与单极图
2017/03/31 Javascript
解决bootstrap下拉菜单点击立即隐藏bug的方法
2017/06/13 Javascript
Javascript快速实现浏览器系统通知
2017/08/26 Javascript
vue实现密码显示隐藏切换功能
2018/02/23 Javascript
iview日期控件,双向绑定日期格式的方法
2018/03/15 Javascript
微信小程序设置滚动条过程详解
2019/07/25 Javascript
[01:45]DOTA2新英雄“神谕者”全方位展示
2014/11/21 DOTA
对python内置map和six.moves.map的区别详解
2018/12/19 Python
python中的句柄操作的方法示例
2019/06/20 Python
Python何时应该使用Lambda函数
2019/07/02 Python
python提取xml里面的链接源码详解
2019/10/15 Python
Python操作Jira库常用方法解析
2020/04/10 Python
利用Python实现最小二乘法与梯度下降算法
2021/02/21 Python
CSS3实现渐变背景兼容问题
2020/05/06 HTML / CSS
美国东北部户外服装和设备零售商:Eastern Mountain Sports
2016/10/05 全球购物
英国邮购活的植物主要供应商:Gardening Direct
2019/01/28 全球购物
中学生的1000字检讨书
2014/10/11 职场文书
2014年政府采购工作总结
2014/12/09 职场文书
酒店辞职书范文
2015/02/26 职场文书
大学优秀学生主要事迹材料
2015/11/04 职场文书
优秀员工演讲稿
2019/06/21 职场文书
golang通过递归遍历生成树状结构的操作
2021/04/28 Golang
SQL Server数据库查询出现阻塞之性能调优
2022/04/10 SQL Server
Python使用Beautiful Soup(BS4)库解析HTML和XML
2022/06/05 Python