栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

map和reduce

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

map和reduce

map 函数

| map(func, *iterables) --> map object
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
制作一个迭代器,使用每个迭代iterables的参数计算函数。当最短的迭代iterables结束时停止。

map 函数是一个允许你使用另一个函数转换整个可迭代对象的函数。
map 函数在转换过程中可以节省内存。

tuple(map(lambda x,y:x+y,[1,2,3,4],[2,3,4,5]))
list(map(lambda x:x**x,[2,4,6,8]))

在python 3中,map函数返回的是迭代器,所以前面必须让其转化成元组,列表。

reduce函数

在python3.0中,reduce在functools包中,使用前要先导入。
python中自带帮助函数为:
Help on built-in function reduce in module _functools:

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把每次的计算结构都进行累加。
当map和reduce中的匿名函数都是x+y时,map必须放两组列表,也就是说第一个列表的1,2,3,4都有一个对应的数字与它相加。
reduce函数,只需要放入一个列表。1首先与2相加,然后新数字3再与第三个数字3相加,结果6再与下一个数字4相加,……,最后结果是15。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665183.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号