Python內建函數(40)——map,python內建函數map

來源:互聯網
上載者:User

Python內建函數(40)——map,python內建函數map

英文文檔:

map( function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding 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. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().
說明:
  1. 函數接受一個函數型別參數、一個或者多個可迭代對象參數,返回一個可迭代器,此迭代器中每個元素,均是函數參數執行個體調用可迭代對象後的結果。
>>> a = map(ord,'abcd')>>> a<map object at 0x03994E50>>>> list(a)[97, 98, 99, 100]

  2. 當傳入多個可迭代對象時,函數的參數必須提供足夠多的參數,保證每個可迭代對象同一索引的值均能正確傳入函數。

>>> 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') # f函數可以接受2個參數>>> list(a)['ae', 'bf', 'cg']

  3. 當傳入多個可迭代對象時,且它們元素長度不一致時,產生的迭代器只到最短長度。

>>> def f(a,b):    return a + b>>> a = map(f,'abcd','efg') # 選取最短長度為3>>> list(a)['ae', 'bf', 'cg']

  4. 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.