Python中的函數、裝飾器

來源:互聯網
上載者:User
map()函數接收兩個參數,一個是函數,一個是序列,map將傳入的函數依次作用到序列的每個元素,並把結果作為新的list返回。
 >>> s = ['AASDa', 'dendY'] >>> def formatStr(ss): return ss[0].upper() + ss[1:len(ss)].lower()   >>> v = formatStr('aaaB') >>> v 'Aaab' >>> map(formatStr, s) <map object at 0x000000000320A668> >>> for v in map(formatStr, s): print(v)   Aasda Dendy 

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

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
 >>> L = [2, 3, 4] >>> def prod(a, b): return a * b >>> >>> from functools import * >>> reduce(prod, L) 24 >>> filter函數,方法同map,目的是過濾list中合格元素:

 >>> s = [1, 2, -3, -5] >>> def notLt0(x): return x >= 0   >>> filter(notLt0, s) <filter object at 0x000000000320A940> >>> for v in filter(notLt0, s): print(v)   1 2 >>> 如上的樣本,定義一個notLt0的方法,該方法用於判斷元素是否大於等於0,是則返回True,否則返回False。而filter則會將列表s的每一個元素作為參數調用notLt0方法,最後將所有返回True的元素重新組裝成一個list返回。 匿名函數:無須定義函數的名稱,格式如下: 
 fn = 匿名函式參數列表: 函數體 其中fn為返回的匿名函數,例如: 
 ''' 匿名函數 ''' f = lambda x : x * x print(f(2)) 函數的閉包,類似javascript的閉包,即外部函數返回內建函式的引用,內建函式可能持有外部函數變數的引用,例如: 
 ''' 閉包 ''' def count(): fs = [] for i in range(1, 4): def f(): print(i) return i *

聯繫我們

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