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

被折叠的 条评论
为什么被折叠?



