Python基礎- 函數式編程

來源:互聯網
上載者:User

標籤:cube   span   div   條件   參數   函數式編程   strip   range   int   

Python中內建的三個函數與序列一起使用非常有用:filter(), map()和reduce()。

1.filter(function, sequence)

filter()的作用是從一個序列中篩出合格元素。

filter()也接收一個函數和一個序列,filter()把傳入的函數依次作用於每個元素,然後根據傳回值是True還是False決定保留還是丟棄該元素。

由於filter()使用了惰性計算,所以只有在取filter()結果的時候,才會真正篩選並每次返回下一個篩出的元素。

例如得到能被3或者5整除的數

def f(x):    return x % 3 == 0 or x % 5 == 0print filter(f, range(2, 25))# [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

例如刪掉一個序列中的Null 字元串

def not_empty(s):    return s and s.strip()print filter(not_empty, [‘A‘, ‘B‘, ‘ ‘, ‘C‘, None, ‘D‘])# [‘A‘, ‘B‘, ‘C‘, ‘D‘]

2.map(function, sequence)

map將傳入的函數依次作用到序列的每個元素,並把結果返回

def cube(x): return x*x*xprint map(cube, range(1, 11))# [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]seq = range(8)def add(x, y): return x+yprint map(add, seq, seq)# [0, 2, 4, 6, 8, 10, 12, 14]

還可以利用,map將一組數字轉化為字串

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))# [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]

 

3.reduce(function, sequence)

這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

 例如,求1到100的和,就可以用reduce實現

def add(x,y): return x+yprint reduce(add, range(1, 101))# 5050

 用這種方式來得到序列的和,如果序列為空白時,就會拋出異常。為了避免拋出異常,可以用下面的方式

def sum(seq):    def add(x,y): return x+y    return reduce(add, seq, 0)print sum(range(1, 11))# 55print sum([])# 0

 

Python基礎- 函數式編程

聯繫我們

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