1.filter (BOOL_FUNC,SEQ)
Filter () is a ' filtering function ', and also receives a function and a sequence, filter () acts on each element of the sequence by the function of the descendant, and then decides whether to persist or discard the element based on whether the return value is TRUE or False
Example:
def fr (x):
return x%2==1
-
print ' Filter1: ' , Filter (Fr,range (1,51)) #筛选出100以内的所有奇数
Print ' filter2: ', Filter (fr,[1,2,3,4])
Output:
Filter1: [1, 3, 5, 7, 9, one, ,, +,,, at, +, (+), (+), (+), ()
Filter2: [1, 3]
filter Built-in functions Python implementation:
>>> 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 (): the function func acts on each element of a given sequence and provides the return value with a list, and if Func is none,func as an identity function, returns a list of n tuples containing the set of elements in each sequence.
>>> 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]
The python implementation of the map built-in function:
>>> def map (FUNC,SEQ):
MAPPED_SEQ = []
for Eachitem in seq:
Mapped_seq.append (func (Eachitem))
return Mapped_seq
3.Reduce (func,seq[,init])
reduce (): Func is a two-tuple function that functions func on the elements of a 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, Finally, we reduce our sequence to a single return value: If Init is given, the first comparison will be init and the first sequence element instead of the head two elements of the sequence.
>>> Reduce (lambda x,y:x + y,[1,2,3,4])
10
>>> Reduce (lambda x,y:x + y,[1,2,3,4],10)
20
The python implementation of reduce:
>>> 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
This article is from the "Operations Diary" blog, make sure to keep this source http://gyyblog.blog.51cto.com/8666992/1921278
Python function filter () map () reduce ()