Advanced Topics function 3--

recursive function

Function call to itself circulates directly or indirectly

L = [1,[2,3,[4,5,6,[7,8,9,10]]]]
def sumtree(L):
    t = 0
    for i in L:
        if not isinstance(i,list):
            t += i
        else:
            t += sumtree(i)
    return t
sumtree(L)

Indirect function calls

#将函数名赋值给其他变量
def func(x):
    print(x)
a = func
b = a
c = b
c(1)
print(c.__name__)
#结果:
1
func

Property function

def func(x):
    pass
print(dir(func))
func.count = 0
func.count += 1
print(func.count)   # 1
print(dir(func))   # 多了一个“count”属性

Anonymous function lambda

lambda is an expression, not a statement . Because of this, lambda can occur at a place where def arise, parameters such as, in a list of constants or function call. lambda returns a new function can be selectively assigned to a variable name . def statement must assign a new function in the head to a variable name (ie, function name), rather than as a result of this function returns.

The lambda expression is a single body, rather than a block of code. Simply the result of a written expression, rather than explicit return.

f = lambda x,y,z:x+y+z
print(f(1,2,3))  # 6

L =[lambda x:x*2,lambda x:x*3,lambda x:x*4]
for f in L:
    print(f(1),end = '  ')  #结果:2  3  4  

#lambda嵌套
f=lambda x:lambda y:x+y
f(1)(2)

Higher-order functions

Meet the following conditions:
accepting as input one or more functions (parameters)
output (return) function of a

Two important built-in functions map and filter

Mapping function map (function, iterable)

map has two parameters, the first parameter is a function of the second parameter is iterables, the role of the map: iterable each element as a function of the parameter, and returns a result of execution of all contain iterable.

def func(x):
    return x+1
L = [1,2,3]
res = map(func,L)
print(list(res)) #[2,3,4]

lambda and map

ret = map(lambda x:x+1,[i for i in range(1,4)])
print(list(ret))  # #[2,3,4]

filter

filter (function or None, iterable) -> returns an iterator that generates those functions iterator (item) is true iterable items. If the function is None, returns to true items.

res = filter(None,[0,3,''])
print(list(res))
#结果:
[3]
# -----------------------------
def fun(n):
    return n % 2
res = filter(fun,range(0,5))
print(list(res))
#结果:
[1,3]

Guess you like

Origin www.cnblogs.com/notfind/p/11517662.html