python的幾個內建函數:apply(),filter(),map(),reduce()

python的幾個內建函數:apply(),filter(),map(),reduce() 

apply()函數: apply(func[,nkw][,kw]) 它的返回值就是func函數的返回值


filter()函數:  filter(func,seq) 調用bool函數func,遍歷處理序列中seq的每個元素。它的返回值是一個序列,其元素都是讓func函數返回true值的原seq序列中的元素

map()函數:

def map(func,seq):
    mapped_seq = []
    for eachItem in seq:
        mapped_seq.append(apply(func,eachItem))
    return mapped_seq


reduce()函數:reduce(func,seq[,init]),用二元函數func對序列seq中的元素進行處理,每次處理兩個數據項(一個是前次處理的結果,一個是序列中的下一個元素),如此反覆的遞歸處理,最後對整個序列求出一個單一的返回值。

1.apply()函數

 1.1 apply()函數對於調用那些參數是動態生成的函數是非常方便的,一般牽扯到拼湊一個參數清單這種問題

matheasy.py

#!/usr/bin/env/ python
from string import lower
from operator import add,sub,mul
from random import randint,choice

ops = {'+':add,'-':sub,'*':mul}
MAXTRIES = 2

def doprob():
    op = choice('+-*')
    nums = [randint(1,10),randint(1,10)]
    nums.sort();nums.reverse()
    ans = apply(ops[op],nums)
    pr = '%d %s %d = ' %( nums[0],op,nums[1])
    oops = 0
    while 1:
        try:
            if int(raw_input(pr)) == ans:
                print "correct"
                break
            if oops == MAXTRIES:
                print 'answer/n%s%d' %(pr,ans)
                break
            else:
                print 'incorrect ... try again'
                oops = oops + 1
        except(KeyboardInterrupt,EOFError,ValueError):
            print 'invalid input data ... try again'
            
def main():
    print 'welcome to play this game:'
    while 1:
        doprob()
        try:
            opt = lower(raw_input('Try again? ([y]/n)'))
        except(KeyboardInterrupt,EOFError):
            print ;break
        if opt and opt[0] =='n':
            print 'quit the game,byebye'
            break

if __name__ == '__main__':
    main()
            
        
        
        
        
        
 1.2 apply()函數對於應用程序的調試糾錯和性能測試方面也是很有用的。一般是編寫一個診斷性函數來建立測試環境,然後調用準備對它進行測試的函數,考慮到系統的靈活性和適應性,被測試函數作爲一個參數傳遞進去

testit.py

#!/usr/bin/env/ python
def testit(funcname,*nkwargs,**kwargs):
    try:
        retval = apply(funcname,nkwargs,kwargs)
        result = (1,retval)
    except Exception,diag:
        result = (0,str(diag))
    return result

def test():
    funcs = (int,long,float)
    vals = (1234,12.34,'1234','12.34')
    
    for eachFunc in funcs:
        print '-'*40
        for eachVal in vals:
            retval = testit(eachFunc,eachVal)
            
            if retval[0]:
                print '%s(%s) = ' %(eachFunc.__name__,eachVal),retval[1]
            else:
                print '%s(%s) = FAILED ' %(eachFunc.__name__,eachVal),retval[1]
                
if __name__ == '__main__':
    test()

2.filter()函數

oddnumgen.py

from random import randint
def odd():
    allNums = []
    for eachNum in range(100):
        allNums.append(randint(1,1000))
    oddNums = filter(lambda n:n%2,allNums)
    print "length of sequence = %d/n" %(len(oddNums)),oddNums

3.map()函數

>>>map(lambda x,y:(x+y,x-y),[1,3,5],[2,4,6])
>>> [(3, -1), (7, -1), (11, -1)]

from string import strip,upper
def strupper():
    f = open('map.txt')
    lines = f.readlines()
    f.close() 
    print ' ... BEFORE processing ...'
    for eachLine in lines:
        print '<%s>' %eachLine[:-1]#去掉換行符
    print "/n" 
    print ' ... AFTER processing ...'    
    for eachLine in map(upper,map(strip,lines)):#strip不清理字符串之間的空格
        print '<%s>' %eachLine

def rounder():
    f = open('round.txt')              
    values = map(float,f.readlines()) 
    f.close() 
    
    print 'original/trounded'
    for eachVal in map(None,values,map(round,values)):#函數爲None,那麼參數列表中的n個序列(此時爲values和map(round,values) )組成了返回值的列表
        print '%6.02f/t/t%6.02f' %eachVal

4.reduce()函數

 >>> print 'the total is:',total = reduce((lambda x,y:x+y),range(1000))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章