python的reduce函数

本文深入解析了Python中的reduce函数,详细介绍了其工作原理和应用场景。reduce函数能够将一个二元函数应用于序列的元素上,从左到右累积计算,最终将整个序列缩减为单一值。文章通过具体实例展示了如何使用reduce函数进行矩阵维度降低,将三维矩阵转换为二维矩阵,适用于数据处理和数学计算等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python的reduce函数

官方说明:
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    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.
    """
    pass

function是一个二元函数,随后的参数可以进行累加的,如图
在这里插入图片描述
尝试举例:

max1  = [
    [[0,1],
     [1,2],
     [1,1]],
    [[2,3],
     [3,4],
     [3,3]]
    ]

ten = reduce(np.add,max1)
print ten
输出结果:
[[2 4]
 [4 6]
 [4 4]]

显然可以看出来,reduce是用来降低维度的,从2×3×2三维变成3*2二维的矩阵,对应位置上的元素相加的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值