Python中map和reduce函數

來源:互聯網
上載者:User

標籤:參數   12px   view   lin   important   under   comm   code   過程   

①從參數方面來講:

map()函數:

map()包含兩個參數,第一個是參數是一個函數,第二個是序列(列表或元組)。其中,函數(即map的第一個參數位置的函數)可以接收一個或多個參數。

reduce()函數:

reduce() 第一個參數是函數,第二個是 序列(列表或元組)。但是,其函數必須接收兩個參數。

 

②從對傳進去的數值作用來講:

map()是將傳入的函數依次作用到序列的每個元素,每個元素都是獨自被函數“作用”一次;(請看下面的栗子)

reduce()是將傳人的函數作用在序列的第一個元素得到結果後,把這個結果繼續與下一個元素作用(累積計算),

最終結果是所有的元素相互作用的結果。(請看下面的栗子)

 

舉個栗子:

map()函數:

 

[python] view plain copy
  1. # 傳入一個參數  
  2. def one_p(x):  
  3.     return x * x  
  4. print ‘map1.1:‘, map(one_p, range(1, 5))   
  5. #結果:map1.1: [1, 4, 9, 16]  
  6. print ‘map1.2:‘, map(one_p, [1, 2, 3, 4, 5, 6])  
  7. #結果:map1.2: [1, 4, 9, 16, 25, 36]  
  8.   
  9. # 傳入多個參數  
  10. a = [1, 2, 3, 4, 5]  
  11. b = [1, 1, 6, 2, 3]  
  12. c = [1, 2, 3, 4, 5]  
  13. s = map(lambda (x, y, z): x * y * z, zip(a, b, c))  
  14. print ‘map2:‘, s  
  15. #結果:map2: [1, 4, 54, 32, 75]  


reduce()函數:

 

 

[python] view plain copy
  1. r1 = reduce(lambda x, y: x * y, (2, 2, 6, 2))  #運算過程:(((2*2)*6)*2)  
  2. r2 = reduce(lambda x, y: x * y, (2, 2, 6), 2)  #<span >運算過程:(((2*2)*6)*2)</span>  
  3.   
  4. print ‘r1:‘, r1  # 結果:r1: 48  
  5. print ‘r2:‘, r2  # 結果:r2: 48 

Python中map和reduce函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.