from itertools import accumulate
import operator
# 示例1: 累加求和
data = [1, 2, 3, 4, 5]
result = list(accumulate(data))
print(result) # 输出: [1, 3, 6, 10, 15]
# 解释: accumulate 函数默认对数据进行累加操作。每次迭代时,它会将当前元素与之前的结果相加。
# 上面的例子中,[1, 2, 3, 4, 5] 经过累加后变为 [1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5]。
# 示例2: 使用 operator.mul 进行累乘
data = [1, 2, 3, 4, 5]
result = list(accumulate(data, func=operator.mul))
print(result) # 输出: [1, 2, 6, 24, 120]
# 解释: 通过传递 func 参数,可以指定不同的累积操作。这里使用了 operator.mul 来进行累乘。
# 上面的例子中,[1, 2, 3, 4, 5] 经过累乘后变为 [1, 1*2, 1*2*3, 1*2*3*4, 1*2*3*4*5]。
上一篇:python中的//
下一篇:python字典获取某个键的值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站