python學習筆記—— 函數

來源:互聯網
上載者:User
〈p>讀取遠程頁面

from urllib import urlretrievedef printFile(url):    f = open(url)    for line in f:        if line.strip():            print line    f.close()def loadFile(url=r'http://www.idkin.com/contact.html', process=printFile):    try:        fileName = urlretrieve(url,'tmp.html')[0]        print(fileName)    except BaseException, e:        print(str(e))    if fileName:        process(fileName)if __name__ == "__main__":    loadFile()#urlretrieve的傳回值是一個tuple, 第一個元素就是目標檔案名#如果urlretrieve僅擷取一個參數,傳回值的第一個元素就是產生的臨時檔案名稱

filter函數,類似javascript1.7的Array#filter。filter函數的功能相當於過濾器。調用一個布爾函數fn來迭代遍曆每個seq中的元素;返回一個使fn傳回值為true的元素的序列。

from random import randintdef filter(fn,arr):    ret = [];    for i in arr:        if fn(i):            ret.append(i)    return ret;arr = [1,2,3,4,5,6];print filter(lambda n:n%2,arr)

map函數,類似javascript1.7的Array#map。map函數func作用於給定序列的每個元素,並用一個列表來提供傳回值。

from random import randintdef map(fn,arr):    ret = [];    for i in arr:        ret.append(fn(i))    return ret;arr = [1,2,3,4,5,6];print map(lambda n:n+10,arr)

我們也可以用並歸的思想實現此迭代器:

def rmap ( fun, list ):    if list == []:        return []    else:        return [fun( list[0] )] + rmap( fun, list[1:] )

reduce函數,類似javascript1.7的Array#reduce。fn為二元函數,將fn作用於seq序列的元素,每次攜帶一對(先前的結果以及下一個序列的元素),連續的將現有的結果和下一個值作用在獲得的隨後的結果上,最後減少我們的序列為一個單一的傳回值。

from random import randintdef reduce(fn,seq,initial=None):     lseq = list(seq)     if initial is None:         res = lseq.pop(0)     else:         res = initial     for i in lseq:         res = fn(res,i)     return resarr = [1,2,3,4,5,6];print reduce(lambda a,b:a+b,arr)

追蹤閉包詞法的變數

output = 'int %r id=%#0x val=%d'w = x = y =z  =1def f1():    x = y = z = 2    def f2():    y = z = 3        def f3():        z = 4        print output %('w', id(w),w)        print output %('x', id(x),x)        print output %('y', id(y),y)        print output %('z', id(z),z)                clo = f3.func_closure        if clo:            print "f3 closure vars: ",[str(c) for c in clo]        else:            print "no f3 closure vars"                f3()    clo = f2.func_closure    if clo:        print "f2 closure vars: ",[str(c) for c in clo]    else:        print "no f2 closure vars"f2()    clo = f1.func_closureif clo:    print "f1 closure vars: ",[str(c) for c in clo]else:    print "no f1 closure vars"f1()   

列印日誌

# coding='utf-8'from time import timedef logged(when):    def log(f,*args,**kargs):        print '''Called:        function:%s        args:%r        kargs:%r''' % (f,args,kargs)    def pre_logged(f):        def wrapper(*args,**kargs):            log(f,*args,**kargs)            return f(*args,**kargs)        return wrapper    def post_logged(f):        def wrapper(*args,**kargs):            now=time()            try:                return f(*args,**kargs)            finally:                log(f,*args,**kargs)                print "time delta: %s" %(time()-now)        return wrapper    try:        return {"pre":pre_logged,"post":post_logged}[when]    except KeyError, e:        raise ValueError(e),'must be "pre" or "post"'@logged("post")def hello(name):    print "Hello,",namehello("World")

產生器

# coding='utf-8'def counter(start_at=10):    count = start_at    while(True):        val = (yield count)        if(val is not None):            count = val        else:            count += 1            if(count == 10):                breakfor i in counter(3):   print 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.