Python中的map、reduce和filter浅析
发布时间:2021-07-13 23:57:08
1、先看看什么是 iterable 对象
以内置的max函数为例子,查看其doc:
>>> print max.__doc__
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
在max函数的第一种形式中,其第一个参数是一个 iterable 对象,既然这样,那么哪些是 iterable 对象呢?
>>> max('abcx')
>>> 'x'
>>> max('1234')
>>> '4'
>>> max((1,2,3))
>>> 3
>>> max([1,2,4])
>>> 4
我们可以使用yield生成一个iterable 对象(也有其他的方式):
def my_range(start,end):
''' '''
while start <= end:
yield start
start += 1
执行下面的代码:
for num in my_range(1, 4):
print num
print max(my_range(1, 4))
将输出:
1
2
3
4
4
2、map
在http://docs.python.org/2/library/functions.html#map中如此介绍map函数:
map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
map函数使用自定义的function处理iterable中的每一个元素,将所有的处理结果以list的形式返回。例如:
def func(x):
''' '''
return x*x
print map(func, [1,2,4,8])
print map(func, my_range(1, 4))
运行结果是:
[1, 4, 16, 64]
[1, 4, 9, 16]
也可以通过列表推导来实现:
print [x*x for x in [1,2,4,8]]
3、reduce
在http://docs.python.org/2/library/functions.html#reduce中如下介绍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.
这个已经介绍的很明了,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
相当于计算
((((1+2)+3)+4)+5)
而:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)
相当于计算
(((((6+1)+2)+3)+4)+5)
4、filter
在http://docs.python.org/2/library/functions.html#filter中如下介绍filter函数:
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.
参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。比如,过滤掉字符串中的字符a:
def func(x):
''' '''
return x != 'a'
print filter(func, 'awake')
运行结果是:
wke
这也可以通过列表推导来实现:
print ''.join([x for x in 'awake' if x != 'a'])


猜你喜欢
- 最近在代码评审的过程,发现挺多错误使用eval导致代码注入的问题,比较典型的就是把eval当解析dict使用,有的就是简单的使用eval,有
- 本文实例为大家分享了Python实现简单的2048小游戏的具体代码,供大家参考,具体内容如下运行效果:1.项目结构2.代码configs.p
- 数据库查询优化的实用技巧:本文中,abigale代表查询字符串,ada代表数据表名,alice代表字段名。技巧一:问题类型:ACCESS数据
- 1. watch 与 computed 的巧妙结合如上图,一个简单的列表页面。你可能会这么做: created(){ this.
- 本文实例为大家分享了python实现学生信息管理系统的具体代码,供大家参考,具体内容如下代码如下:Project.py文件内容:class
- 前言:本文的主要内容是介绍Python中的变量命名规则和简单数据类型的应用,简单的数据类型包括字符串和数字等,文中还附有代码以及相应的运行结
- 基本映射映射使用在根据不同URLs请求来产生相对应的返回内容.Bottle使用route() 修饰器来实现映射.from bottle im
- 一年前网上还找不到关于 inline-block 属性的文章,为了方便大家更好的理解该属性,当时总结整理了篇《display:inline-
- Q1 :如何解压 rar 压缩包文件?A :Step1:检查是否有 rarfile 第三方库,若没有该模块,则需要进行安装 ;Step2:参
- 这篇文章主要介绍了Python手绘可视化工具cutecharts使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 多表连接查询表与表之间的连接分为内连接和外连接内连接:仅选出两张表互相匹配的记录外连接:既包括两张表匹配的记录,也包括不匹配的记录,同时外连
- 本文实例为大家分享了js省市县 * 级联特效的实现代码,供大家参考,具体内容如下主要思想1.省改变,市改变,并初始化县2.市改变,县改变htm
- 目录写在前面基本概念Windows搭建python开发环境从Hello World开始博客总结从大学开始玩python到现在参加工作,已经有
- 1、官网下载,并解压https://dev.mysql.com/downloads/mysql/2、设置环境变量配置MYSQL_HOME为M
- if条件分支1. if语句基本用法if boolean_value:子代码模块11)判断条件 boolean_value是if语句判断条件
- 目录1.横向合并1.1 concatenate方法1.2 hstack方法1.3 column_stack方法2.纵向合并2.1 conca
- 在安装tensorflow完成后,import tensorflow as tf出现问题,问题如下:>>> import
- 最近在工作中涉及到判断服务器所在ip反馈程序使用情况的程序主要要求就是,本机或局域网调试程序时,不反馈其域名(localhost)或ip站长
- 本文为大家分享了pygame游戏之旅的第3篇,供大家参考,具体内容如下载入car图片(我自己画的),需要用到pygame.image模块,定
- 如下所示:# Seed random number generatornp.random.seed(42)# Compute mean no