Python has several built-in functions that are interesting: map/filter/reduce, it's all about a collection, filter is easy to understand for filtering, map is used for mapping, and reduce is used for merging. Is the three carriage of the Python list method.
- Filter () function:
The function of the filter function is equivalent to a filter. Call a Boolean function Bool_func to iterate through the elements in each SEQ, and return a sequence of elements that enable BOOL_SEQ to return a value of true.
>>>a=[1,2,3,4,5,6,7]
>>>b=Filter (Lambdax:x> 5 < Span style= "color: #000000;" >a)
>>> print b
>>> [ 6 , 7 < Span style= "color: #000000;" >]
If the value of the filter parameter is none, the identity () function is used and all false elements in the list parameter are deleted. As shown below:
>>>a=[0,1,2,3,4,5,6,7]
>>>b=Filter (None, a)
>>>Print B
>>>[1 2 < Span style= "color: #000000;" >3 < Span style= "color: #000000;" >4 < Span style= "color: #000000;" >5 < Span style= "color: #000000;" >6 < Span style= "color: #000000;" >7 "
- Map () Function:
The map function func acts on each element of a given sequence and provides a return value using a list. >>>Map (Lambdax:x+3, a)#这里的a同上
>>>[3,4,5,6,7,8,9,Ten]
#另一个例子
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>Map (Lambdax,y:x+ y < Span style= "color: #000000;" >a ,b)
>>> < Span style= "color: #000000;" >[ 5 < Span style= "color: #000000;" >, 7 < Span style= "color: #000000;" >, 9 < Span style= "color: #000000;" >]
The reduce function, func, is a two-tuple function that acts on the elements of the SEQ sequence, each carrying a pair (the previous result and the element of the next sequence), continuously acting on the resulting subsequent result with the existing result and the next value, and finally reducing our sequence to a single return value. >>>a= [1,2,3,4,5]
>>>reduce ( lambda x y : < Span style= "color: #000000;" >x + < Span style= "color: #000000;" >y < Span style= "color: #000000;" >a)
15
/span>
Python built-in function Map/reduce/filter