跟老齐学Python之大话题小函数(2)


Posted in Python onOctober 10, 2014

上一讲和本讲的标题是“大话题小函数”,所谓大话题,就是这些函数如果溯源,都会找到听起来更高大上的东西。这种思维方式绝对我坚定地继承了中华民族的优良传统的。自从天朝的臣民看到英国人开始踢足球,一直到现在所谓某国勃起了,都一直在试图论证足球起源于该朝的前前前朝的某国时代,并且还搬出了那时候的一个叫做高俅的球星来论证,当然了,勃起的某国是挡不住该国家队在世界杯征程上的阳痿,只能用高俅来意淫一番了。这种思维方式,我是坚定地继承,因为在我成长过程中,它一直被奉为优良传统。阿Q本来是姓赵的,和赵老爷是本家,比秀才要长三辈,虽然被赵老爷打了嘴。

废话少说,书接前文,已经研究了map,下面来看reduce。

忍不住还得来点废话。不知道看官是不是听说过MapReduc,如果没有,那么Hadoop呢?如果还没有,就google一下。下面是我从维基百科上抄下来的,共赏之。

MapReduce是Google提出的一个软件架构,用于大规模数据集(大于1TB)的并行运算。概念“Map(映射)”和“Reduce(化简)”,及他们的主要思想,都是从函数式编程语言借来的,还有从矢量编程语言借来的特性。

不用管是不是看懂,总之又可以用开头的思想意淫一下了,原来今天要鼓捣的这个reduce还跟大数据有关呀。不管怎么样,你有梦一般的感觉就行。

reduce

回到现实,清醒一下,继续敲代码:

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

15

 请看官仔细观察,是否能够看出是如何运算的呢?画一个图:

跟老齐学Python之大话题小函数(2)

还记得map是怎么运算的吗?忘了?看代码:

>>> list1 = [1,2,3,4,5,6,7,8,9]

>>> list2 = [9,8,7,6,5,4,3,2,1]

>>> map(lambda x,y: x+y, list1,list2)

[10, 10, 10, 10, 10, 10, 10, 10, 10]

 看官对比一下,就知道两个的区别了。原来map是上下运算,reduce是横着逐个元素进行运算。

权威的解释来自官网:

reduce(function, iterable[, initializer])

 

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to:

 

 def reduce(function, iterable, initializer=None):

    it = iter(iterable)

    if initializer is None:

        try:

            initializer = next(it)

        except StopIteration:    

            raise TypeError('reduce() of empty sequence with no initial value')    

    accum_value = initializer                                                                   

    for x in it:

        accum_value = function(accum_value, x)    

    return accum_value

 如果用我们熟悉的for循环来做上面reduce的事情,可以这样来做:

>>> lst = range(1,6)

>>> lst

[1, 2, 3, 4, 5]

>>> r = 0

>>> for i in range(len(lst)):

...     r += lst[i]

... 

>>> r

15

 for普世的,reduce是简洁的。

为了锻炼思维,看这么一个问题,有两个list,a = [3,9,8,5,2],b=[1,4,9,2,6],计算:a[0]b[0]+a1b1+...的结果。

>>> a

[3, 9, 8, 5, 2]

>>> b

[1, 4, 9, 2, 6]
>>> zip(a,b)        #复习一下zip,下面的方法中要用到

[(3, 1), (9, 4), (8, 9), (5, 2), (2, 6)]
>>> sum(x*y for x,y in zip(a,b))    #解析后直接求和

133
>>> new_list = [x*y for x,y in zip(a,b)]    #可以看做是上面方法的分布实施

>>> #这样解析也可以:new_tuple = (x*y for x,y in zip(a,b))

>>> new_list

[3, 36, 72, 10, 12]

>>> sum(new_list)     #或者:sum(new_tuple)

133
>>> reduce(lambda sum,(x,y): sum+x*y,zip(a,b),0)    #这个方法是在耍酷呢吗?

133
>>> from operator import add,mul            #耍酷的方法也不止一个

>>> reduce(add,map(mul,a,b))

133
>>> reduce(lambda x,y: x+y, map(lambda x,y: x*y, a,b))  #map,reduce,lambda都齐全了,更酷吗?

133

 filter

filter的中文含义是“过滤器”,在python中,它就是起到了过滤器的作用。首先看官方说明:

filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

这次真的不翻译了(好像以往也没有怎么翻译呀),而且也不解释要点了。请列位务必自己阅读上面的文字,并且理解其含义。英语,无论怎么强调都是不过分的,哪怕是做乞丐,说两句英语,没准还可以讨到英镑美元呢。

通过下面代码体会:

>>> numbers = range(-5,5)

>>> numbers

[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> filter(lambda x: x>0, numbers) 

[1, 2, 3, 4]
>>> [x for x in numbers if x>0]     #与上面那句等效

[1, 2, 3, 4]
>>> filter(lambda c: c!='i', 'qiwsir')  #能不能对应上面文档说明那句话呢?

'qwsr'                                  #“If iterable is a string or a tuple, the result also has that type;”

 至此,用两此介绍了几个小函数,这些函数在对程序的性能提高上,并没有显著或者稳定预期,但是,在代码的简洁上,是有目共睹的。有时候是可以用来秀一秀,彰显python的优雅和自己耍酷。

Python 相关文章推荐
python从sqlite读取并显示数据的方法
May 08 Python
python遍历 truple list dictionary的几种方法总结
Sep 11 Python
CentOS6.5设置Django开发环境
Oct 13 Python
Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
Apr 02 Python
Python实现的文本对比报告生成工具示例
May 22 Python
python批量查询、汉字去重处理CSV文件
May 31 Python
Python socket套接字实现C/S模式远程命令执行功能案例
Jul 06 Python
python 内置模块详解
Jan 01 Python
详解解决Python memory error的问题(四种解决方案)
Aug 08 Python
PyCharm更改字体和界面样式的方法步骤
Sep 27 Python
python爬虫库scrapy简单使用实例详解
Feb 10 Python
Python图像处理之图像拼接
Apr 28 Python
跟老齐学Python之大话题小函数(1)
Oct 10 #Python
Python警察与小偷的实现之一客户端与服务端通信实例
Oct 09 #Python
python中二维阵列的变换实例
Oct 09 #Python
python实现每次处理一个字符的三种方法
Oct 09 #Python
Python正则表达式匹配ip地址实例
Oct 09 #Python
Python数据结构之Array用法实例
Oct 09 #Python
python中pygame模块用法实例
Oct 09 #Python
You might like
PHP 字符串编码截取函数(兼容utf-8和gb2312)
2009/05/02 PHP
破解.net程序(dll文件)编译和反编译方法
2013/01/31 PHP
实例讲解PHP面向对象之多态
2014/08/20 PHP
php中动态变量用法实例
2015/06/10 PHP
基于PHP代码实现中奖概率算法可用于刮刮卡、大转盘等抽奖算法
2015/12/20 PHP
php读取torrent种子文件内容的方法(测试可用)
2016/05/03 PHP
php版微信js-sdk支付接口类用法示例
2016/10/12 PHP
IOS 开发之NSDictionary转换成JSON字符串
2017/08/14 PHP
Draggable Elements 元素拖拽功能实现代码
2011/03/30 Javascript
JS根据年月获得当月天数的实现代码
2014/07/03 Javascript
JQuery实现防止退格键返回的方法
2015/02/12 Javascript
jQuery标签编辑插件Tagit使用指南
2015/04/21 Javascript
基于javascript实现彩票随机数生成(升级版)
2020/04/17 Javascript
JavaScript优化专题之Loading and Execution加载和运行
2016/01/20 Javascript
jQuery插件实现图片轮播特效
2016/06/16 Javascript
JavaScript实现无限级递归树的示例代码
2019/03/29 Javascript
[46:59]完美世界DOTA2联赛PWL S2 GXR vs Ink 第二场 11.19
2020/11/20 DOTA
Python检测字符串中是否包含某字符集合中的字符
2015/05/21 Python
Python脚本暴力破解栅栏密码
2015/10/19 Python
Python抓取框架 Scrapy的架构
2016/08/12 Python
python实现简易内存监控
2018/06/21 Python
对Python捕获控制台输出流的方法详解
2019/01/07 Python
pytorch实现onehot编码转为普通label标签
2020/01/02 Python
python字符串替换re.sub()实例解析
2020/02/09 Python
使用python实现CGI环境搭建过程解析
2020/04/28 Python
HTML5 和小程序实现拍照图片旋转、压缩和上传功能
2018/10/08 HTML / CSS
美国蔬菜和植物种子公司:Burpee
2017/02/01 全球购物
美国在线家具网站:GDFStudio
2021/03/13 全球购物
解释i节点在文件系统中的作用
2013/11/26 面试题
法学毕业生自荐信
2013/11/13 职场文书
动物科学专业毕业生的自我评价
2013/11/29 职场文书
学生穿着不得体检讨书
2014/10/12 职场文书
2014年酒店工作总结范文
2014/11/17 职场文书
幼儿园开学家长寄语(2016秋季)
2015/12/03 职场文书
pytorch 权重weight 与 梯度grad 可视化操作
2021/06/05 Python
python3 字符串str和bytes相互转换
2022/03/23 Python