This article shares with you a detailed explanation of the use of python advanced functions with examples. The content is quite good. I hope it can help friends in need.
Function parameter problem
##Three basic situations
fun(a,b)
fun(a,b) b is an iterable object
fun(a,**b) b is an iteration object with a retrieval type, inside the function body When parsing, it is quite a dictionary
ls = [i for i in range(10)] #print(ls) def fun1(a,*b): for i in b: print(a,i) #fun1(1,*ls) def fun2(name,age,**kw): print("name:",name,"age:",age,"other:",kw) fun2('fanhaitao','26',参数= 'random')
**kw参数把键值对转换成字典的形式
Anonymous function
lambda
There is no return value, the return value is the value of the expression
The function has no name, so don’t worry about name conflicts
The anonymous function is also a function object. You can also assign the anonymous function to a variable and use the variable to call the function
fun3 = lambda x:x+1 print(fun3(99)) #100 fun4 = lambda x,y :x*x + y*y print(fun4(3,4)) #25
Decorator@
This method of dynamically adding functions while the code is running is called "Decorator"
Decorator without parameters
#定义一个装饰器 def log(func): def wrapper(*args,**kw): print('call %s()' % func.__name__) return func(*args,**kw) return wrapper @log def now(): print('2018-3-29') now()
The internal logical relationship of the decorator (calling sequence): log() -> return wrapper() -> return func() -> now()
Decorator with parameters
#定义一个装饰器 def log(text): def decorator(func): def wrapper(*args,**kw): print('%s %s():' % (text,func.__name__)) return func(*args,**kw) return wrapper return decorator @log("可爱的参数") def now(): print('2018-3-29') now()
BiF built-in function
zip: Combine two iteration objects into one iteration object
Note: redundant unmatched variables will be discarded
a = [1,2,3] b = 'abcde' for i in zip(a,b): print(i) for i,j in zip(a,b): print("Index:",i,";Item:",j)
enumerate: returns an iterable object, consisting of position + element
for i,j in enumerate('abcde'): print(i,j)
filter: filter Function
Two parameters, the first is a parameter, the second is an iterable object, the returned value is also an iterable object; the iterative object in the parameter is True in the function, The value will be retained, otherwise pass
print(list(filter(lambda x:(x*x+x+2)%8 == 0,range(100))))
map
print(list(map(lambda x:x**2,range(5))))
Collection of Python functions and advanced syntax The above is the detailed content of Detailed examples of the use of python advanced functions. For more information, please follow other related articles on the PHP Chinese website!from functools import reduce
add = lambda x,y:x+y
ls = [i for i in range(101)]
print(reduce(add,ls))