在講述filter,map和reduce之前,首先介紹一下匿名函數lambda。
lambda的使用方法如下:lambda [arg1[,arg2,arg3,...,argn]] : expression
例如:
[python] view plain copy
- >>> add = lambda x,y : x + y
- >>> add(1,2)
- 3
接下來分别介紹filter,map和reduce。
1、filter(bool_func,seq):此函數的功能相當于過濾器。調用一個布爾函數bool_func來疊代周遊每個seq中的元素;傳回一個使bool_seq傳回值為true的元素的序列。
例如:
[python] view plain copy
- >>> filter(lambda x : x%2 == 0,[1,2,3,4,5])
- [2, 4]
filter内建函數的python實作:
[c-sharp] view plain copy
- >>> 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...]):将函數func作用于給定序列的每個元素,并用一個清單來提供傳回值;如果func為None,func表現為身份函數,傳回一個含有每個序列中元素集合的n個元組的清單。
例如:
[c-sharp] view plain copy
- >>> 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]]
- >>> map(lambda x : None,[1,2,3,4])
- [None, None, None, None]
map内建函數的python實作:
[python] view plain copy
- >>> def map(func,seq):
- mapped_seq = []
- for eachItem in seq:
- mapped_seq.append(func(eachItem))
- return mapped_seq
3、reduce(func,seq[,init]):func為二進制函數,将func作用于seq序列的元素,每次攜帶一對(先前的結果以及下一個序列的元素),連續的将現有的結果和下一個值作用在獲得的随後的結果上,最後減少我們的序列為一個單一的傳回值:如果初始值init給定,第一個比較會是init和第一個序列元素而不是序列的頭兩個元素。
例如:
[c-sharp] view plain copy
- >>> 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實作:
[python] view plain copy
- >>> 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