天天看點

Python 函數 filter() map() reduce()

1.filter(bool_func,seq)

filter()是‘篩選函數’,也接收一個函數和一個序列,filter()把傳人的函數依次作用于序列的每個元素,然後根據傳回值是True還是false決定保留還是丢棄該元素 

例子:

def fr(x):  

    return x%2==1  

print 'filter1:',filter(fr,range(1,51))#篩選出100以内的所有奇數  

print 'filter2:',filter(fr,[1,2,3,4])

     輸出:

         filter1: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

           filter2: [1, 3]

 filter内建函數的Python實作:

>>> def filter(bool_func,seq):  

    filtered_seq = []  

    for eachItem in seq:  

        if bool_func(eachItem):  

            filtered_seq.append(eachItem)  

    return filtered_seq

2、map(func,seq1[,seq2...])

map():将函數func作用于給定序列的每個元素,并用一個清單來提供傳回值;如果func為None,func表現為身份函數,傳回一個含有每個序列中元素集合的n個元組的清單。

>>> map(lambda x : None,[1,2,3,4])  

[None, None, None, None]  

>>> map(lambda x : x * 2,[1,2,3,4])  

[2, 4, 6, 8]  

>>> map(lambda x : x * 2,[1,2,3,4,[5,6,7]])  

[2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]  

[None, None, None, None]  

map内建函數的python實作:

>>> def map(func,seq):  

    mapped_seq = []  

        mapped_seq.append(func(eachItem))  

    return mapped_seq  

3.reduce(func,seq[,init])

reduce():func為二進制函數,将func作用于seq序列的元素,每次攜帶一對(先前的結果以及下一個序列的元素),連續的将現有的結果和下一個值作用在獲得的随後的結果上,最後減少我們的序列為一個單一的傳回值:如果初始值init給定,第一個比較會是init和第一個序列元素而不是序列的頭兩個元素。

>>> reduce(lambda x,y : x + y,[1,2,3,4])  

10  

>>> reduce(lambda x,y : x + y,[1,2,3,4],10)  

20  

reduce的python實作:

>>> def reduce(bin_func,seq,initial=None):  

    lseq = list(seq)  

    if initial is None:  

        res = lseq.pop(0)  

    else:  

        res = initial  

    for eachItem in lseq:  

        res = bin_func(res,eachItem)  

    return res  

本文轉自 奚落123 51CTO部落格,原文連結:http://blog.51cto.com/guyuyuan/1921280,如需轉載請自行聯系原作者