Python中的高阶函数。
高阶函数是指可以把函数作为参数传递给其他函数,或者把函数作为返回值返回的函数。在Python中,函数是一等对象,所以Python中操作函数的灵活性非常高。本文将介绍Python中的高阶函数,包括内置的高阶函数和自定义的高阶函数,并给出一些使用高阶函数的例子。
一、内置的高阶函数
1. map()
map()函数用于对一个可迭代对象进行映射,即将其中的每个元素应用指定的函数,返回一个新的可迭代对象,其中每个元素是原始可迭代对象中应用函数后的结果。
map()函数的语法如下:
map(function, iterables)
其中,function为映射函数,iterables为可迭代对象。
例子:
def square(x):
return x ** 2
list(map(square, [1, 2, 3, 4, 5])) # [1, 4, 9, 16, 25]
2. filter()
filter()函数用于对一个可迭代对象进行过滤,即返回一个新的可迭代对象,其中包含原始可迭代对象中满足指定条件的元素。
filter()函数的语法如下:
filter(function, iterable)
其中,function为判断函数,iterable为可迭代对象。
例子:
def is_odd(x):
return x % 2 != 0
list(filter(is_odd, [1, 2, 3, 4, 5])) # [1, 3, 5]
3. reduce()
reduce()函数用于对一个可迭代对象进行聚合操作,即将其中的所有元素依次应用指定的函数,返回聚合后的结果。
reduce()函数需要从functools模块中导入,语法如下:
reduce(function, iterable[, initializer])
其中,function为聚合函数,iterable为可迭代对象,initializer为可选的初始值。
例子:
from functools import reduce
def add(x, y):
return x + y
reduce(add, [1, 2, 3, 4, 5]) # 15
二、自定义的高阶函数
除了Python内置的高阶函数,我们还可以根据自己的需求自定义高阶函数。
1. apply_to_all()
apply_to_all()函数用于将一个函数应用于一个可迭代对象中的所有元素,返回一个新的可迭代对象,其中每个元素是原始可迭代对象中应用函数后的结果。
例子:
def apply_to_all(func, iterable):
return [func(item) for item in iterable]
apply_to_all(lambda x: x**2, [1, 2, 3, 4, 5]) # [1, 4, 9, 16, 25]
2. apply_n_times()
apply_n_times()函数用于将一个函数应用于其自身多次,得到最终结果。
例子:
def apply_n_times(func, x, n):
if n == 0:
return x
else:
return apply_n_times(func, func(x), n-1)
apply_n_times(lambda x: x**2, 2, 3) # 256
3. memoize()
memoize()函数用于缓存一个函数的计算结果,避免重复计算。
例子:
def memoize(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@memoize
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
三、使用高阶函数的例子
1. 求解函数导数
可以使用高阶函数来求解函数的导数,具体方法是将函数近似为一阶导数为常数的函数,并计算其斜率。
例子:
def derivative(f, h=0.0001):
def calculate(x):
return (f(x+h) - f(x)) / h
return calculate
f = lambda x: x**2 + 2*x + 1
d = derivative(f)
print(d(2)) # 6.0001
2. 装饰器
可以使用高阶函数来实现装饰器,即将一个函数作为参数传递给另一个函数,并用一个新的函数来包装它。
例子:
def benchmark(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print("{} took {:.6f} seconds".format(func.__name__, end-start))
return result
return wrapper
@benchmark
def add(x, y):
return x + y
print(add(2, 3)) # add took 0.000003 seconds 5
四、总结
高阶函数是Python中的非常重要的概念,它可以提高代码的抽象和灵活性,使得代码更加简洁、可读、易维护。Python内置了很多高阶函数,同时我们也可以根据自己的需求自定义高阶函数。使用高阶函数可以让我们在解决问题的过程中更加便捷和高效。
