1.高阶函数
- 接收函数作为参数,或者将函数作为返回值返回的函数就是⾼阶函数
def bar():
print("function bar")
def foo(func):
func()
print("function bar")
foo(bar)
foo(bar)
def bar():
print("function bar")
return 1
def foo(func):
print("function foo")
return bar
res=foo(bar)
res()
res()
- 函数名(如bar 、foo)–>为该函数的内存地址,函数名+括号(如 bar()、foo() )–>调用该函数。
- Python内置高阶函数map、filter、reduce、匿名函数lambda、sorted
- lambda 只是一个表达式,函数体比 def 简单很多。主体为一个表达式,而不是一个代码块。在lambda表达式中只能封装有限的逻辑。lambda 函数有自己的命名空间,不能访问自己参数列表之外或全局命名空间里的参数。
lambda [arg1 [,arg2,.....argn]]:expression
foo = lambda a, b: a + b
print(foo(10, 20))
- map函数接收两个参数,函数和序列,把序列中的值用函数处理再依次返回至列表内。map函数返回一个迭代器对象
def square(x):
return x ** 2
print(list(map(square, [1, 2, 3, 4, 5])))
- filter函数接收一个函数和一个序列,用于过滤。返回一个迭代器对象
print(