前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中的map()函数

python中的map()函数

作者头像
py3study
发布2020-01-02 16:25:56
1K0
发布2020-01-02 16:25:56
举报
文章被收录于专栏:python3python3

先来看一下官方文档:

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

代码语言:javascript
复制
例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()。

代码语言:javascript
复制
例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

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

代码语言:javascript
复制
>>> a = map(f,'abcd','efg') # 选取最短长度为3
>>> list(a)
['ae', 'bf', 'cg']

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

代码语言:javascript
复制
例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函数根本就不会执行

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档