Python:accumulate累积函数实战

简介:accumulate 是内置模块itertools中的一个函数,主要用于生成一个迭代器,该迭代器按照指定的操作对输入的可迭代对象进行累积计算。它返回一个逐步累积的结果序列。

参数说明:iterable, func=None

1、iterable: 可迭代对象,表示要进行累积操作的数据序列。

2、func: 二元操作函数,表示对两个元素进行操作的规则。该函数接受两个参数并返回一个结果。如果未提供该参数,默认使用加法运算进行累积计算。

历史攻略:

Python:heapq模块使用

测试用例:多条件下编写,懒人妙用itertools

Python:filter、map、reduce、zip函数

Python:常见排列组合问题处理

Python高阶:counter、orderedDict、defaultdict、deque、queue简单示例

案例: 与reduce的区别;reduces是将所有的结果全部计算完成,给出最终结果;而accumulate是返回一个逐步累积的结果序列

# -*- coding: utf-8 -*-
# time: 2023/10/22 23:34
# file: accumulate_demo.py
# 公众号: 玩转测试开发
from functools import reduce
from itertools import accumulate

arr1 = [i for i in range(1, 5)]
print(arr1)  # [1, 2, 3, 4]

# 默认累加
res1 = list(accumulate(arr1))  # [1, 3, 6, 10]
print(res1)


def multi(a, b):
    # 乘法函数
    return a * b


# 传入二元函数,则支持自定义累积方式。如累积乘法
res2 = list(accumulate(arr1, multi))
res3 = list(accumulate(arr1, lambda a, b: a * b))  # 等价于 multi(a, b)
print(res2)
print(res3)

# 更多例子
print(list(accumulate(arr1, lambda a, b: a / b)))  # 累积除法
print(list(accumulate(arr1, lambda a, b: a ** b)))  # 累积幂

new_list30 = reduce(multi, [1, 2, 3])
new_list31 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
new_list32 = reduce(lambda x, y: x + y, ["a1", "b2", "c3"])
print(new_list30)  # 6
print(new_list31)  # 15
print(new_list32)  # a1b2c3

运行结果:

图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值