Python 之 functools 模块(reduce/partial/lru_cache/_make_key)

1、reduce 方法

1.1 语法

Docstring:
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
Type:      builtin_function_or_method
  • 可迭代对象sequence不能为空
  • 初始值initial没提供就在可迭代对象中取一个元素

1.2 示例

from functools import reduce
print(reduce(lambda x,y: x + y, range(1, 5), 10))  # 20
# 10 + 1
# 11 + 2
# 13 + 3
# 16 + 4
# 20
print(reduce(lambda x,y: x * y, range(1, 5), 10))  # 240
from functools import reduce
nums = [6, 9, 1, 2, 10, 5]
print(nums)
print(sum(nums))
print(reduce(lambda val, x: val + x, nums))
print(reduce(lambda val, x: val + x, nums, 10))
[6, 9, 1, 2, 10, 5]
33
33
43

2、partial方法(偏函数)

2.1 概念

  • partial 偏函数,把函数部分的参数固定下来,相当于为部分的参数添加了一个固定的默认值,形成一个新的函数并返回
  • 从partial生成的新函数,是对原函数的封装

2.2 语法

Init signature: partial(self, /, *args, **kwargs)
Docstring:     
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.

2.3 本质

# partial 函数本质
# 无法验证参数类型
# 函数挺简单的,大家可以解读一下,了解偏函数的本质
def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):  # 包装函数
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        print(newkeywords, keywords, fkeywords, fargs)
        return func(*(args + fargs), **newkeywords)
    print(args, keywords)
    newfunc.func = func  # 保留原函数
    newfunc.args = args  # 保留原函数的位置参数
    newfunc.keywords = keywords  # 保留原函数的关键字参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值