Python 進階 之 map()函數

來源:互聯網
上載者:User

標籤:mod   on()   迭代器   ***   相同   func   執行   map函數   class   

    map()函數主要功能是對批量的元素進行相同的操作時可以大幅度的縮減代碼。

    map函數參數詳解:

    map(param1,param2,***)

    param1:函數名 ,要對批量元素進行處理的function

    param2~paramX:可迭代對象,(列表,元祖,迭代器...換句話說:能執行 for x in param:語句的都可以)

  map只有兩個參數時:

    例如:

1 >>> def function(x):2 ...     return x*x3 ... 4 >>> list1 = [1,2,3]5 >>> map(function,list1)6 [1, 4, 9]7 >>> 

  map參數為多個時:

             需要注意的是:map參數的個數 與function參數個數的關係:map參數個數為x個,function個數為x-1個,否則會報錯

    例如(出錯的情況):

 1 >>> def function(x): 2 ...     return x*x 3 ...  4 >>> list1 = [1,2,3] 5 >>> list2 = [4,5,6] 6 >>> list3 = [7,8,9] 7 >>> map(function,list1,list2,list3) 8 Traceback (most recent call last): 9   File "<stdin>", line 1, in <module>10 TypeError: function() takes exactly 1 argument (3 given)

    正確的用法應該是:

1 >>> def function(x,y,z):2 ...     return x+y+z3 ... 4 >>> list1 = [1,2,3]5 >>> list2 = [4,5,6]6 >>> list3 = [7,8,9]7 >>> map(function,list1,list2,list3)8 [12, 15, 18]

 

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.