python中的map()函數

來源:互聯網
上載者:User

標籤:end   call   result   body   div   res   contain   迭代器   py3   

python中的map()函數

標籤: python

先來看一下官方文檔:

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函數根本就不會執行

python中的map()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.