您的位置:首页 > 编程语言 > Python开发

Python中map()函数用法-对列表中每个元素做相同操作,并返回list

2016-11-20 12:04 1226 查看
MapReduce的设计灵感来自于函数式编程,这里不打算提MapReduce,就拿python中的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 withNoneitems. If function isNone, 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.

一点一点看:

1、对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回。

来个例子:

>>> def add100(x):
... return x+100
...
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]

>>> 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)]


>>> def add100(x):
...     return x + 100
...
>>> list1 = [11,22,33]
>>> map(add100,list1)
[101, 102, 103]

>>> [add100(i) for i in list1]
[101, 102, 103]


[code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: