python map reduce的怎么打印map和reduce结果

python中的map、filter、reduce函数 - 简书
python中的map、filter、reduce函数
三个函数比较类似,都是应用于序列的内置函数。常见的序列包括list、tuple、str。
map函数会根据提供的函数对指定序列做映射。
map函数的定义:map(function, sequence[, sequence, ...]) -& list
通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个集合。function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list。
lambda 结合的例子
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
返回结果为:
[1, 4, 9, 16, 25]
单参数例子&&& def add100(x):
return x+100
&&& hh = [11,22,33]
&&& map(add100,hh)
[111, 122, 133]
list参数的例子&&& def abc(a, b, c):
return a*10000 + b*100 + c
&&& list1 = [11,22,33]
&&& list2 = [44,55,66]
&&& list3 = [77,88,99]
&&& map(abc,list1,list2,list3)
function为None的例子&&& list1 = [11,22,33]
&&& map(None,list1)
[11, 22, 33]
&&& list1 = [11,22,33]
&&& list2 = [44,55,66]
&&& list3 = [77,88,99]
&&& map(None,list1,list2,list3)
[(11, 44, 77), (22, 55, 88), (33, 66, 99)]
filter函数
filter函数会对指定序列执行过滤操作。
filter函数的定义:filter(function or None, sequence) -& list, tuple, or string
function是一个谓词函数,接受一个参数,返回布尔值True或False。
filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。返回值的类型和参数sequence的类型相同
返回序列中的所有奇数
def is_even(x):
return x & 1 != 0
filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
返回结果为:
[1, 3, 5, 7, 9]
如果function参数为None,返回结果和sequence参数相同。
reduce函数
reduce函数,reduce函数会对参数序列中元素进行累积。
py3以后使用,必须导入 from functools import reduce
reduce函数的定义:reduce(function, sequence[, initial]) -& value
function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。
def myadd(x,y):
return x+y
sum=reduce(myadd,(1,2,3,4,5,6,7))
print(sum)
#结果就是输出1+2+3+4+5+6+7的结果即28
lambda 结合的例子
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
(((((1+2)+3)+4)+5)+6)
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
注意function函数不能为None。python中的map、filter、reduce函数
三个函数比较类似,都是应用于序列的内置函数。常见的序列包括list、tuple、str。
map函数会根据提供的函数对指定序列做映射。
map函数的定义:
map(function, sequence[, sequence, ...]) -& list
通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个集合。
function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list。
比如要对一个序列中的每个元素进行平方运算:
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
返回结果为:
[1, 4, 9, 16, 25]
在参数存在多个序列时,会依次以每个序列中相同位置的元素做参数调用function函数。
比如要对两个序列中的元素依次求和。
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8,
map返回的list中第一个元素为,参数序列1的第一个元素加参数序列2中的第一个元素(1 + 2),
list中的第二个元素为,参数序列1中的第二个元素加参数序列2中的第二个元素(3 + 4),
依次类推,最后的返回结果为:
[3, 7, 11, 15, 19]
要注意function函数的参数数量,要和map中提供的集合数量相匹配。
如果集合长度不相等,会以最小长度对所有集合进行截取。
当函数为None时,操作和zip相似:
map(None, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
返回结果为:
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
2.filter函数
filter函数会对指定序列执行过滤操作。
filter函数的定义:
filter(function or None, sequence) -& list, tuple, or
function是一个谓词函数,接受一个参数,返回布尔值True或False。
filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。
返回值的类型和参数sequence的类型相同
比如返回序列中的所有偶数:
def is_even(x):
return x & 1 != 0
filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
返回结果为:
[1, 3, 5, 7, 9]
如果function参数为None,返回结果和sequence参数相同。
3.reduce函数
reduce函数,reduce函数会对参数序列中元素进行累积。
reduce函数的定义:
reduce(function, sequence[, initial]) -& value
function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。
第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
结果为21( &(((((1+2)+3)+4)+5)+6)
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
注意function函数不能为None。
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。Python内置函数map与reduce用法简介
map与reduce是两个十分常用的python内置函数,它们与Hadoop中的MapReduce在某些方面有一定的相似之处。map函数:
map(function, iterable, ...)
对于可迭代对象(iterable)中的每一个元素调用处理函数(function),并以列表(list)形式返回每个元素的调用结果。如果传递了不止一个可迭代对象参数,函数从各个可迭代对象中取出相同位置的元素加以并行处理。如果可迭代对象长短不一,则为较短的参数末尾补充None元素,使其长度补齐。如果处理函数为None,则视为恒等函数(identity function,返回值等于传入参数的函数叫做恒等函数);如果传入了多个参数,map()会返回一个包含各个可迭代对象对应结果的元组列表(可以视为转置操作)。可迭代参数可以是一个序列(sequence),或者任何可以迭代的对象;结果总是返回list。
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 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 the result is always a list.map函数示例:
基本用法:&&& map(lambda x : x*2, [1, 2, 3, 4, 5])[2, 4, 6, 8, 10]
传递多个iterable对象:&&& map(lambda x, y : x+y, [1, 3, 5], [2, 4, 6])[3, 7, 11]
传递多个长短不一的iterable对象:&&& map(lambda x, y : str(x)+str(y), ['a', 'e', 'i'], ['o', 'u'])['ao', 'eu', 'iNone']
function为None:&&& map(None, [1, 2, 3, 4, 5])[1, 2, 3, 4, 5]
function为None,且传递多个iterable对象:&&& map(None, [1, 3, 5], [2, 4, 6])[(1, 2), (3, 4), (5, 6)] reduce函数: reduce(function, iterable[, initializer]) 对可迭代对象(iterable)从左向右累积地调用处理函数(function),从而将可迭代对象缩减为单个值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 等价于计算 ((((1+2)+3)+4)+5)。 左边的参数x是被累积的值, 右边的参数y是从迭代对象更新的值。如果传入了可选的初始值(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 = initializerfor x in it:accum_value = function(accum_value, x)return accum_valuereduce函数示例:
基本用法:&&& reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])15
传入初始值:&&& reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 6)21
传入初始值,iterable对象为空列表:&&& reduce(lambda x, y: x+y, [], 6)6
传入只包含一个元素的iterable对象:&&& reduce(lambda x, y: x+y, [1])1
当初始值与可迭代对象同时为空时,会抛出下面的错误提示:Traceback (most recent call last):File &&, line 1, in TypeError: reduce() of empty sequence with no initial value
【声明】:黑吧安全网()登载此文出于传递更多信息之目的,并不代表本站赞同其观点和对其真实性负责,仅适于网络安全技术爱好者学习研究使用,学习中请遵循国家相关法律法规。如有问题请联系我们,联系邮箱,我们会在最短的时间内进行处理。
上一篇:【】【】Python内置函数map、reduce、filter的用法
map函数的用法 查看下帮助: help(map)Help on built-in function map in module __builtin__:map(...) map(function, sequence[, sequence, ...]) - list Return a list of the results of applying the function to the items of the argument se
map函数的用法
查看下帮助:
&&& help(map)
Help on built-in function map in module __builtin__:
map(function, sequence[, sequence, ...]) -& list
Return a list of the results of applying the function to the items of
the argument sequence(s).
If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length.
If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
map函数接受的参数为一个处理sequence的函数,及最少一个或多个sequence。map函数会对参数sequence的每个item执行function(item),
最后将执行结果构成一个list返回。
map函数的运用场景大概包括以下几种:
1、处理一个sequence,如,对sequence中的每个值求平方:
&&& a=[1,2,3,4]
&&& map(lambda x:x*x,a)
[1, 4, 9, 16]
2、处理多个sequence,但参数function也需要支持相应数量的参数,如,对两个sequence中相应item做乘法操作:
&&& a=[1,2,3,4]
&&& b=[5,6,7,8]
&&& map(lambda x,y:x*y,a,b)
[5, 12, 21, 32]
&&& map(lambda x:x*x,a,b)
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
TypeError: &lambda&() takes exactly 1 argument (2 given)
3、处理多个sequence时,每个sequence的长度如果不相同,则较短的sequence会被当做在该sequence中增加相应个数(直到达到较sequence元素个数)的None值来处理,如:
&&& a=[1,2,3,4]
&&& b=[5,6,7]
&&& map(lambda x,y:x+y,a,b)
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
File &&stdin&&, line 1, in &lambda&
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
这里我们尝试对a、b这两个list中相应的item做求和操作,但是a有四个元素,而b只有三个,所以b会被挡住为:[5,6,7,None]处理,
而int类型是不能与None类型执行&+&操作的,所以,在执行&4+None&时这里会报错!
4、参数function可以是None,此时分两种情况:
1)、只操作一个sequence,返回一个由sequence中的item组成的list:
&&& a=[1,2,3,4]
&&& map(None,a)
[1, 2, 3, 4]
2)、操作多个sequence,返回一个把有tuple组成的list,tuple包含每个sequence中相应的item:
&&& a=[1,2,3,4]
&&& b=[5,6,7]
&&& map(None,a,b)
[(1, 5), (2, 6), (3, 7), (4, None)]
注意此处,b的第四个元素是被当做为None处理的。
reduce函数的用法
查看下帮助:
&&& help(reduce)
Help on built-in function reduce in module __builtin__:
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.
reduce函数接受的参数为一个处理sequence的函数,及一个sequence,和一个可选的初始值intial。
参数function接受两个参数。
reduce函数为sequence中item从左到右顺序迭代执行function(item)。
reduce函数的使用非常简单,运用场景大概可以就分为两种:
1、不带初始值,如,对sequence中的item求和:
&&& a=[1,2,3,4]
&&& reduce(lambda x,y:x+y,a)
2、带初始值,如,对sequence中的item求和:
&&& a=[1,2,3,4]
&&& reduce(lambda x,y:x+y,a,10)
如果有传递initial参数,此处为10,则initial参数会被首先执行。
需要注意的地方是,参数function,必须接受两个参数:
&&& a=[1,2,3,4]
&&& reduce(lambda x:x,a)
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
TypeError: &lambda&() takes exactly 1 argument (2 given)
&&& reduce(lambda x,y,z:x+y+z,a)
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
TypeError: &lambda&() takes exactly 3 arguments (2 given)
filter函数的用法
查看下帮助:
&&& help(filter)
Help on built-in function filter in module __builtin__:
filter(...)
filter(function or None, sequence) -& list, tuple, or string
Return those items of sequence for which function(item) is true.
function is None, return the items that are true.
If sequence is a tuple
or string, return the same type, else return a list.
filter函数接受的参数为一个sequence和一个处理sequence的function(可以是None)。
filter函数对sequence中的每个item依次执行function(item),将执行结果为true的item依据sequence的类型返回一个list、truple或者string。
filter函数的使用非常简单,大概可以参考以下几种场景:
1、传递一个sequence,列出sequence中的偶数,返回一个list,如:
&&& a=[1,2,3,4,5,6,7,8,9,10]
&&& filter(lambda x:x%2==0,a)
[2, 4, 6, 8, 10]
2、传递一个sequence,列出sequence中的偶数,返回一个tuple,如:
&&& a=(1,2,3,4,5,6,7,8,9,10)
&&& filter(lambda x:x%2==0,a)
(2, 4, 6, 8, 10)
3、传递一个sequence,列出sequence中不包含&a&的其他字符,返回一个string,如:
&&& a='abcdef'
&&& filter(lambda x:x!='a',a)
'bcdef'
4、如果参数function为None,则对sequence原样返回,感觉这个用法挺没意思的:
&&& a='abcdef'
&&& filter(None,a)
'abcdef'
补充一下,sequence主要包括以下几种类型:
实现一个小需求:用map返回乘方列表,reduce计算乘积,filter挑出奇数
#列表a=[1,3,5,7,8,9,4]
a=[1,3,5,7,8,9,4]
#1、对列表a,用map返回乘方列表
mapa=map(lambda x:x*x,a)
print mapa
#2、对列表a,用reduce计算乘积
reducea=reduce(lambda x,y:x*y,a)
print reducea
#3、对列表a,用filter挑出奇数
filtera=filter(lambda x:x%2==1,a)
print filtera
打印出来的结果为:
[1, 9, 25, 49, 64, 81, 16]
[1, 3, 5, 7, 9]
转载请保留固定链接:
------分隔线----------------------------
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
记录一个rabbitmq启动脚本,修改部分参数即可用。 vi /etc/init.d/...
Golang的主要 设计目标之一就是面向大规模后端服务程序,网络通...
功能: 自动检测是否有尚未分区的数据盘,格式化新的数据盘并...
#!/usr/bin/env python# -*- coding:utf-8 -*-该计算器思路: 1、递归寻找表...
hosts文件存储了IP地址与域名的映射。因为有的时候需要经常性地...
#!/bin/bash######################################################################...Python的filter, map, reduce和zip等内置序列函数 - 其它语言 - 编程入门网
Python的filter, map, reduce和zip等内置序列函数
filter, map, reduce, zip都是针对python中的sequence数据类型的内置方法。
名词解释:本文中的iterable是指可迭代对象,包括sequence和iterator,及其他具有可迭代性的container。
1. filter(function, iterable)
filter的工作原理是使用第一个参数对象(function或者None)来对第二参数对象iterable进行运算,并根据运算结 果的布尔值来过滤iterable中的元素。
对function返回值的布尔运算,如果为True,则将当前元素存储到string, tuple或者list中并最终返回对应类型的 对象;如果为False,则将当前元素过滤掉,如果function没有返回值,则视为返回None,因此所有元素都会被过滤掉。 如果第一个参数不是function而是None,则返回iterable中所有为True的元素。
# function有返回值
&&& filter(lambda d: d != 'a', 'abcd')  # 过滤掉了字母'a'。
&&& def d(x):                     # 不使用lambda时,先定义一个充当过滤器的
     return True if x != 'a' else False
&&& filter(d, 'abcd')
# function没有返回值
&&& def f(x):   
if x != 'a':
&&& foo = filter(f, 'abcd')  # 'abcd'中所有字符都被过滤掉了
# 第一个参数为None
&&& filter(None, 'abcd')
# 没有过滤任何东西
&&& filter(None, [1,2,3,4,5,0])
# 过滤掉了0
[1, 2, 3, 4, 5]
注意:只有当iterable是一个string或者tuple的时候,filter返回的才是string或者tuple,其余都全都是返回list 。而function是一个单参数的函数。
2. map(function, iterable, ...)
map会将iterable对象里的元素遍历到function中进行运算,并返回一个list对象来存储所有的运算结果。map支持多 个iterable参数,如果多个iterable参数元素数量不同,对于数量较少的那个iterable对象,在超出部分取值时值为 None。当第一个参数不为function为None时,返回一个由tuple组成的列表,每个tuple中的元素分别来自各个iterable 对象。
&&& map(lambda a: a+1, [1,2,3,4])
[2, 3, 4, 5]
&&& map(lambda a, b: a+b, [1,2,3,4], (2,3,4,5))
[3, 5, 7, 9]
&&& map(lambda a, b: a + b if b else a + 10, [1,2,3,4,5], (2,3,4,5))
# 第2个iterable对象少了
[3, 5, 7, 9, 15]
&&& map(None, [1,2,3,4,5], [1,2,3])
[(1, 1), (2, 2), (3, 3), (4, None), (5, None)]
注意:function中的参数数量与map中的iterable参数个数相同。
3. reduce(function, iterable, start_value)
reduce函数第一次会在iterable对象中取前两个值传入function中进行运算,然后运算返回值作为第一个参数,再在 iterable对象中取第三个值传入function中进行运算,依次类推,直至iterable对象中所有元素被取值完毕。如果设定 了start_value值,那么start_value将作为第一次执行function函数时的一个参数,并在iterable中取第一个元素作为 function的另一个参数。
&&& reduce(lambda x, y: x+y, range(0,10))
&&& reduce(lambda x, y: x+y, range(0,10), 10)
注意:function是一个双参数的函数,如果没有返回值,则返回None到下一次运算中。
&&& reduce(d, range(0,10))
4. zip(seq[, seq, ...])
zip函数会对每个sequence对象依次取相同索引的值到一个tuple中,然后返回一个由这些tuple组成的列表。tuple的 数量由所有sequence中具有最少索引的那个sequence决定,该sequence取值完毕后便不再继续对剩余的sequence取值。
&&& zip([1,2,3,4],[2,3,4,5])
[(1, 2), (2, 3), (3, 4), (4, 5)]
&&& zip([1,2,3,4], (2,3,4,5,6,7))
[(1, 2), (2, 3), (3, 4), (4, 5)]
&&& zip([1,2,3,4], [[2,3,4],[2,3]])
[(1, [2, 3, 4]), (2, [2, 3])]}

我要回帖

更多关于 python reduce和map 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信