One: Built-in Functions (cont.)
1,zip (Zipper method)
The function is used to wrap an object that can be iterated as an argument, package the corresponding element in the object into a tuple, and then return those tuples. If the number of elements in each iterator is inconsistent, the number of tuples returned is the same as the shortest object
L1 = [A,]l2= ['a','b','C', 5]l3= ('*','**', (A)) forIinchZip (l1,l2,l3):Print(i)#(1, ' a ', ' * ')#(2, ' B ', ' * * ')#(3, ' C ', (1, 2, 3))
2,filter (filter), filter an iterative object through your function
def func (x): return x% 2 == = Filter (func,[1,2,3,4,5,6,7])print(ret) for inch ret: Print (i)
The 3,map will map the specified sequence based on the provided function.
def Square (x): # squared count return x * * 2ret=map (square, [1, 2, 3, 4, 5] # calculates the square print(ret) for in ret of each element of the list : Print(i)
Two: Anonymous functions
The keyword that defines an anonymous function is a lambda, in the form of a function name = lambda parameter: The return value, which is a single sentence that is designed to address the very simple requirements of a function.
# this piece of code def func (N): return n**nprint( func to anonymous function lambda n:n** N Print (func (10))
Ps:
1, parameters can have multiple, separated by commas;
2, anonymous function no matter how complex the logic, can only write a line, and the end of the logical execution of the content is the return value;
3, the return value and the normal function can be any data type;
4, it can be seen that the anonymous function is not really can not have a name, the call of the anonymous function and the normal function of the call.
Three: anonymous function and built-in function application example
dic={'K1': 10,'K2': 100,'K3'73]}Print(Dic[max (dic,key=LambdaK:dic[k]) Res= Map (Lambdax:x**2,[1,5,7,4,8]) forIinchRes:Print(i) Res= Filter (Lambdax:x>10,[5,8,11,9,15]) forIinchRes:Print(i)
Python built-in functions (cont.) and anonymous functions