python map函数

python的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 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至少需要两个参数,第一个参数是function,第二个参数是 sequen类型。但是可以有多于两个参数的调用方法,这时候从第二个开始都要求是sequence类型

只用两个参数调用

(代码A)
>>> def foo(parameter):
...     return parameter
...
>>> map(foo,'xyz')
['x', 'y', 'z']

用多个参数调用

代码B
>>> map(foo,'xyz','lmn') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes exactly 1 argument (2 given)

哦这里遇到错误,仔细看错误说是foo只能接受一个参数。ok,我们的foo确实只是能接受一个错误。虽然遇到了错误但是这个错误并没有说我们对map的调用不对。说明map确实可以调用多个参数。至于这个错误,我们后面会有解决办法。

第二句说如果map调用是这种形式,map(f,sequence)只有一个sequence参数,那么就会对sequence中的每一个 item 都调用一次f函数,然后把结果放进一个list返回。

Return a list of the results of applying the function to the items of
    the argument sequence(s).

其实我们代码A很好的解释了这一句。ok 我们继续看。

第三句说如果map调用是多个sequence的形式,比如 map(foo,'xyz',lm') 那么就会对foo进行多次调用,第一次调用的参数是 (x,l) 第二次调用的是 (y,m) 第三次调用的就是(z,None)。为什么第三次是z和None呢,因为第二个sequence不够长,所以不够长的地方用None代替。但是下面英文的说明中说每一次调用的参数是argument list,可是我们的实验确说明是 argument tuple。 

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.  

实验如下:

代码C
>>> def foo(*parameter): ... return parameter ... >>> map(foo,'xyz','lm') [('x', 'l'), ('y', 'm'), ('z', None)]

嗯 代码C也很好的解决了代码B中遇到的错误。代码B说foo不能调用多余一个的参数,我们就把foo改一下嘛。

第四句话说的是,如果map调用的 map(f,sequence,[sequen..])的f部分不是一个函数而是None,那么返回值就是由sequence中的item组成的list。如果是多个sequence,那么就是所有sequence中对应item先组成tuple然后组成list。

If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).
代码D
>>> map(None,'xyz')
['x', 'y', 'z']
>>> map(None,'xyz','lmn')
[('x', 'l'), ('y', 'm'), ('z', 'n')]
>>> map(None,'xyz','lm')
[('x', 'l'), ('y', 'm'), ('z', None)]
>>> map(None,'xyz',((1,2),'lm'))
[('x', (1, 2)), ('y', 'lm'), ('z', None)]
>>>
原文地址:https://www.cnblogs.com/kramer/p/3642591.html