One - One Code All

Blog Content

python内置函数map()

Python   2010-05-16 15:28:05

python内置函数map()

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

map(function, iterable, …)

    function – 函数,有两个参数
    iterable – 一个或多个序列
    将结果作为list返回

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

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


2、如果’function’给出的是‘None’,自动假定一个‘identity’函数

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


3、如果给出了额外的可迭代参数,则对每个可迭代参数中的元素‘并行’的应用‘function’

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

4、和列表推导式的对比

>>> [abc(a,b,c) for a in list1 for b in list2 for c in list3]
[114477, 114488, 114499, 115577, 115588, 115599, 116677, 116688, 116699, 224477, 224488, 224499, 225577, 225588, 225599, 226677, 226688, 226699, 334477, 334488, 334499, 335577, 335588, 335599, 336677, 336688, 336699]


>>> def square(x) :
...     return x ** 2
...
>>> map(square, [1,2,3,4,5])
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])
[1, 4, 9, 16, 25]
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]


map()只做了列上面的运算,而列表推导(也就是嵌套for循环)做了笛卡尔乘积,所以注意和列表推导式的区别。


上一篇:Python简单web server服务器 HTTP Server (Simples)
下一篇:pip --upgrade批量更新过期的python库

The minute you think of giving up, think of the reason why you held on so long.