python map&reduce

來源:互聯網
上載者:User

標籤:from   元素   UI   style   red   賦值   gpo   def   ...   

可以把函數本身賦值給變數
>>> f = abs
變數可以指向函數
>>> f = abs
>>> f(-10)
10
abs函數實際上是定義在import builtins模組中的,所以要讓修改abs變數的指向在其它模組也生效,要用import builtins; builtins.abs = 10

傳入函數
一個函數接收另一個函數作為參數,這種函數就稱之為高階函數。
def add(x, y, f):
return f(x) + f(y)
當我們調用add(-5, 6, abs)時,參數x,y和f分別接收-5,6和abs,根據函數定義,我們可以推導計算過程為:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11

map

map()函數接收兩個參數,一個是函數,一個是Iterable,
map將傳入的函數依次作用到序列的每個元素,並把結果作為新的Iterator返回
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
map()傳入的第一個參數是f,即函數對象本身
通過list()函數讓它把整個序列都計算出來並返回一個list
把這個list所有數字轉為字串:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]

reduce

reduce把一個函數作用在一個序列[x1, x2, x3, ...]上。
這個函數必須接收兩個參數,
reduce把結果繼續和序列的下一個元素做累積計算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

把序列[1, 3, 5, 7, 9]變換成整數13579,reduce就可以派上用場:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579

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.