专业编程基础技术教程

网站首页 > 基础教程 正文

Python函数工具类 functools 完全指南

ccvgpt 2024-11-18 09:23:42 基础教程 8 ℃


functools 官方文档:https://docs.python.org/zh-cn/3/library/functools.html

Python函数工具类 functools 完全指南

Python 标准模块 --- functools:https://www.cnblogs.com/zhbzz2007/p/6001827.html

Python 的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数。换言之,就是能使用该模块对 所有可调用对象( 即 参数 或(和) 返回值 为其他函数的函数 ) 进行处理。

Python 的 functools 模块为 可调用对象(callable objects) 和 函数 定义高阶函数或操作。简单地说,就是基于已有的函数定义新的函数。

所谓高阶函数,就是以函数作为输入参数,返回也是函数。


使用Functools.partial进行函数柯里化

函数柯里化是一种函数式编程的技巧,它允许你将多参数函数转化为一系列单参数函数。这使得函数更加通用,可以更方便地复用和组合。

functools.partial函数可以帮助我们实现函数柯里化。

from functools import partial

def add(x, y):
    return x + y

# 使用functools.partial进行柯里化
add_five = partial(add, 5)

# 调用柯里化后的函数
result = add_five(10)  # 结果为15

利用Functools.wraps保留函数元信息

在Python中,函数也是对象,它们具有元信息,如函数名、文档字符串等。但是,当使用装饰器或其他方式包装函数时,有时会丢失这些元信息。这可能导致在调试和文档生成等方面出现问题。

functools.wraps函数可以保留被装饰函数的元信息。

示例:

import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """This is the wrapper function."""
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

@my_decorator
def say_hello():
    """This is the say_hello function."""
    print("Hello!")

# 使用functools.wraps装饰后,函数元信息不会丢失
print(say_hello.__name__)  # 输出'say_hello',而不是'wrapper'
print(say_hello.__doc__)   # 输出'This is the say_hello function.',而不是'This is the wrapper function.'

定义了一个装饰器my_decorator,并使用functools.wraps(func)装饰内部的wrapper函数。这可以确保被装饰函数say_hello的元信息不会丢失。

函数缓存:Functools.lru_cache的妙用

import functools

@functools.lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 第一次计算fibonacci(30)时会耗时,但后续调用会立即返回缓存的结果
result = fibonacci(30)  # 第一次计算
result = fibonacci(30)  # 立即返回缓存的结果

我们使用functools.lru_cache装饰fibonacci函数,允许缓存函数的输出。这对于递归函数等计算密集型任务非常有用。

函数工具:Functools.reduce的应用

functools.reduce函数用于对可迭代对象中的元素进行累积操作。

import functools

# 使用functools.reduce计算阶乘
factorial = functools.reduce(lambda x, y: x * y, range(1, 6))

# 输出120,即5的阶乘
print(factorial)

使用functools.reduce计算了5的阶乘。通过提供一个匿名函数来实现乘法操作,可以轻松地累积序列中的元素。

reduce函数的本质

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

实际上你可以用上面的代码来理解rreduce的作用,它的本质上就相当不断循环一个列表或者说是一个可迭代的元素的每个参数,使用这些参数去调用 function,

  • 上一次的结果作为后一次调用的参数,
  • 同时列表中的下一个元素也当作函数的参数

reduce的关键函数和iterable对象

>>> def my_add(a, b):
...     result = a + b
...     print(f"{a} + {b} = {result}")
...     return result 
>>> my_add(5, 5)
5 + 5 = 10
10
>>> from functools import reduce

>>> numbers = [0, 1, 2, 3, 4]

>>> reduce(my_add, numbers)
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10

这个代码的作用是把列表中的元素求和其实就是元素sum

可选参数 :initializer

>>> from functools import reduce

>>> numbers = [0, 1, 2, 3, 4]

>>> reduce(my_add, numbers, 100)
100 + 0 = 100
100 + 1 = 101
101 + 2 = 103
103 + 3 = 106
106 + 4 = 110
110

把上面的参数修改一下 initializer设置为 100,最后的结果也就加上了 100

空集合能用reduce吗?

>>> from functools import reduce

>>> # Using an initializer value
>>> reduce(my_add, [], 0)  # Use 0 as return value
0

>>> # Using no initializer value
>>> reduce(my_add, [])  # Raise a TypeError with an empty iterable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

回顾一下列表求和的正常写法

>>> numbers = [1, 2, 3, 4]
>>> total = 0
>>> for num in numbers:
...     total += num
...
>>> total
10

循环这个列表然后遍历所有的元素求和即可。

如何改造成reduce模式,求和其实最简单的就两个数的加法,于是定义函数如下


>>> def my_add(a, b):
...     return a + b
...

>>> my_add(1, 2)
3
>>> from functools import reduce

>>> numbers = [1, 2, 3, 4]

>>> reduce(my_add, numbers)
10

接着可以直接用reduce去调用这个函数了,其实相当于最初姝合为0,然后访问列表中的每一个元素,把它们的值加上之前的求和值上。

当然这个求和的函数也可以用lambda函数去实现如下

>>> from functools import reduce

>>> numbers = [1, 2, 3, 4]

>>> reduce(lambda a, b: a + b, numbers)
10

当你这个例子也有第三种写法

>>> from operator import add
>>> from functools import reduce

>>> add(1, 2)
3

>>> numbers = [1, 2, 3, 4]

>>> reduce(add, numbers)
10

第四种写法直接求和

>>> numbers = [1, 2, 3, 4]

>>> sum(numbers)
10

使用reduce得到最大值,最小值

>>> from functools import reduce

>>> # Minimum
>>> def my_min_func(a, b):
...     return a if a < b else b
...

>>> # Maximum
>>> def my_max_func(a, b):
...     return a if a > b else b
...

>>> numbers = [3, 5, 2, 4, 7, 1]

>>> reduce(my_min_func, numbers)
1

>>> reduce(my_max_func, numbers)
7

同时的功能我们使用lambda来实现

>>> from functools import reduce

>>> numbers = [3, 5, 2, 4, 7, 1]

>>> # Minimum
>>> reduce(lambda a, b: a if a < b else b, numbers)
1

>>> # Maximum
>>> reduce(lambda a, b: a if a > b else b, numbers)
7

当然python内置的函数也能实现

>>> numbers = [3, 5, 2, 4, 7, 1]

>>> min(numbers)
1

>>> max(numbers)
7

检验所有元素都是True或者都是False

正常写法,遍历元素

>>> def check_all_true(iterable):
...     for item in iterable:
...         if not item:
...             return False
...     return True
...

>>> check_all_true([1, 1, 1, 1, 1])
True

>>> check_all_true([1, 1, 1, 1, 0])
False

>>> check_all_true([])
True

使用reduce实现

>>> def both_true(a, b):
...     return bool(a and b)
...

>>> both_true(1, 1)
True

>>> both_true(1, 0)
False

>>> both_true(0, 0)
False

True False

>>> a = 0
>>> b = 1
>>> bool(a and b)
False

>>> a = 1
>>> b = 2
>>> bool(a and b)
True
>>> from functools import reduce

>>> reduce(both_true, [1, 1, 1, 1, 1])
True

>>> reduce(both_true, [1, 1, 1, 1, 0])
False

>>> reduce(both_true, [], True)
True

使用lambda

>>> from functools import reduce

>>> reduce(lambda a, b: bool(a and b), [0, 0, 1, 0, 0])
False

>>> reduce(lambda a, b: bool(a and b), [1, 1, 1, 2, 1])
True

>>> reduce(lambda a, b: bool(a and b), [], True)
True

更简单的办法

>>> all([1, 1, 1, 1, 1])
True

>>> all([1, 1, 1, 0, 1])
False

>>> all([])
True

判断列表中有元素为True

最直观的办法,遍历元素

>>> def check_any_true(iterable):
...     for item in iterable:
...         if item:
...             return True
...     return False
...

>>> check_any_true([0, 0, 0, 1, 0])
True

>>> check_any_true([0, 0, 0, 0, 0])
False

>>> check_any_true([])
False
>>> def any_true(a, b):
...     return bool(a or b)
...

>>> any_true(1, 0)
True

>>> any_true(0, 1)
True

>>> any_true(0, 0)
False

使用reduce

>>> from functools import reduce

>>> reduce(any_true, [0, 0, 0, 1, 0])
True

>>> reduce(any_true, [0, 0, 0, 0, 0])
False

>>> reduce(any_true, [], False)
False

使用lambda简体这个reduce版本

>>> from functools import reduce

>>> reduce(lambda a, b: bool(a or b), [0, 0, 1, 1, 0])
True

>>> reduce(lambda a, b: bool(a or b), [0, 0, 0, 0, 0])
False

>>> reduce(lambda a, b: bool(a or b), [], False)
False

Python的内置办法

>>> any([0, 0, 0, 0, 0])
False

>>> any([0, 0, 0, 1, 0])
True

>>> any([])
False 

比较 reduce() 和 accumulate()


>>> from itertools import accumulate
>>> from operator import add
>>> from functools import reduce

>>> numbers = [1, 2, 3, 4]

>>> list(accumulate(numbers))
[1, 3, 6, 10]

>>> reduce(add, numbers)
10

大家观察一下结果就知道这两个函数的区别了。

本质上reduce给我们提供了一种操控函数与可迭代对象的工具

reduce本身不会处理数据,它只是一个运算模板,实际的逻辑还是矸目录函数上

最近发表
标签列表