42 lines
1.0 KiB
Python
42 lines
1.0 KiB
Python
# reduce
|
|
|
|
# 核心概念概述
|
|
# reduce函数是Python的内置函数,它的主要作用是对可迭代对象中的元素进行累积操作,将序列中的元素通过指定的函数逐步合并,最终得到一个单一的结果。
|
|
|
|
# 作用:对序列进行累积操作,将多个元素合并为一个结果
|
|
# 导入:需要从functools模块导入
|
|
# 参数:接受一个函数和一个可迭代对象
|
|
# 函数式编程:支持函数式编程范式
|
|
|
|
# from functools import reduce
|
|
# reduce(function, iterable[, initializer])
|
|
|
|
# function:累积函数,必须接受两个参数
|
|
# iterable:可迭代对象(如列表、元组等)
|
|
# initializer:可选参数,作为累积的初始值
|
|
|
|
from functools import reduce
|
|
|
|
|
|
def add(x, y):
|
|
return x + y
|
|
|
|
|
|
numbers = [1, 2, 3, 4, 5]
|
|
|
|
result = reduce(add, numbers)
|
|
print(result)
|
|
|
|
# 模拟reduce
|
|
# 默认初始值
|
|
|
|
|
|
def MyRduce(numbers):
|
|
accumulator = numbers[0]
|
|
for i in range(1, len(numbers)):
|
|
accumulator += numbers[i]
|
|
return accumulator
|
|
|
|
|
|
print(MyRduce(numbers))
|