Record it by then.
3. Built-in functions-higher order functions
1.filter (func,sequence) receives a function f and a list, the function f is to judge each element, return True or False,filter () automatically filter out the non-conforming elements according to the result of the judgment. Returns a new iterator (in Python3) that consists of qualifying elements (a list is returned in Python2)
Li = ['a','b','C']defF (s):#Define a filter function ifs! ='a': returns re= Filter (F,li)#Use the filter function to pass the values in the list into the function separately, filter on the non-conforming condition, and return an iteratorPrint(RE) forIinchRe#iterators are read by A For loop Print(i)
Print (re) # to cast an iterator to the list
<filter object at 0x00000000006e03c8> b c
2.map (func,sequence) receives a function f and a list, and returns a new iterator (in Python3) by acting on each element of the list, in turn, (returns a list in Python2)
Li = ['a','b','C']defF (s):#Define a function returnS +"Zengwenhai"Re= Map (F,li)#use the map function to pass the values in the list to the function separately, processing each value in the listPrint(RE) forIinchRe#iterators are read by A For loop Print(i)
Print (re) # to cast an iterator to the list
<map object at 0x00000000007a0470> Azengwenhai Bzengwenhai Czengwenhai
The 3.reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list. and return the final result value
fromFunctoolsImportReduce#import is required in PythondefAdd (x, y):returnX +yPrint(Reduce (add,[1,3,5,7,9]))#The reduce function passes the values in the list to the function separately, and then into the list after processing, passing in the value again#first two elements are computed: F (1, 3), and the result is 4;#then the result and the 3rd element are calculated: F (4, 5), the result is 9;#then the result and the 4th element are calculated: F (9, 7), the result is three;#then the result and the 5th element are calculated: F (16, 9), the result is;#since there are no more elements, the calculation ends and the result 25 is returned. 25
Python Learning Path 03 (function)