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返回。
例:

例1:

>>> def add(x):
...     return x+1
... 
>>> aa = [11,22,33]
>>> map(add,aa)
[12, 23, 34]

如文档中所说,map函数将add方法映射到aa中的每一个元素,即对aa中的每个元素调用add方法,并返回结果的list。需要注意的是map函数可以多个可迭代参数,前提是function方法能够接收这些参数。否则将报错。例子如下:
如果给出多个可迭代参数,则对每个可迭代参数中的元素‘平行’的应用‘function’。即在每个list中,取出下标相同的元素,执行abc()。

例2:
>>> 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]

>>> a = map(ord,'abcd')
>>> list(a)
[97, 98, 99, 100]
>>> a = map(ord,'abcd','efg') # 传入两个可迭代对象,所以传入的函数必须能接收2个参数,ord不能接收2个参数,所以报错
>>> list(a)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    list(a)
TypeError: ord() takes exactly one argument (2 given)

>>> def f(a,b):
    return a + b

当传入多个可迭代对象时,且它们元素长度不一致时,生成的迭代器只到最短长度。

>>> a = map(f,'abcd','efg') # 选取最短长度为3
>>> list(a)
['ae', 'bf', 'cg']

2.如果'function'给出的是‘None’,则会自动调用一个默认函数,请看例子:

例3:
>>> 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.最后一点需要注意的是,map()在python3和python2中的差异(特别是从py2转到py3的使用者很可能遇到):
在python2中,map会直接返回结果,例如:
map(lambda x: x, [1,2,3])
可以直接返回
[1,2,3]
但是在python3中, 返回的就是一个map对象:
<map object at 0x7f381112ad50>
如果要得到结果,必须用list作用于这个map对象。
最重要的是,如果不在map前加上list,lambda函数根本就不会执行

初心易得,始终难守。
原文地址:https://www.cnblogs.com/Aurora-Twinkle/p/8654886.html