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

对Python中map()函数的理解

2016-07-10 20:27 477 查看
在python2.6.6文档中的描述:
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 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).

1、对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回。
来个例子:
>>> def add100(x):...     return x+100... >>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
就像文档中说的:对hh中的元素做了add100,返回了结果的list。

2、如果给出了一个以上的可迭代参数,函数调用与包含每个可迭代参数中对应项的参数列表,当所给的可迭代参数不是有相同的长度的话就用None替代缺失的值。(翻译的有点拗口)
>>> 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)
[114477, 225588, 336699]
看到并行的效果了吧!在每个list中,取出了下标相同的元素,执行了abc()。

3、如果函数是‘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)]


# 可以用列表方法来对高阶函数进行更巧妙的引用
[add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]


原帖出处:http://my.oschina.net/zyzzy/blog/115096
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息