itertools:Python3迭代库(持续更新ing...)

诸神缄默不语-个人CSDN博文目录

itertools库是Python3生成可迭代对象的库。
官方文档:itertools — Functions creating iterators for efficient looping — Python 3.10.7 documentation

1. combinations(iterable, r)

返回的可迭代对象中每一个元素是iterable元素的一个组合(按iterable的顺序生成),长度为r。
没有iterable中元素和本元素的组合(没有自环),不包含列表中的重复元素。

示例:

from itertools import combinations
a = ['h', 'y', 'k', 'q', 's']
for i in combinations(a, 2):
    print(i)

输出:

('h', 'y')
('h', 'k')
('h', 'q')
('h', 's')
('y', 'k')
('y', 'q')
('y', 's')
('k', 'q')
('k', 's')
('q', 's')

2. accumulate(iterable[, func, *, initial=None])

最简单的用法:计算前缀和(直接返回值是一个迭代器)

从第一个数字开始:

import itertools

example_list=[1 for _ in range(10)]
print(list(itertools.accumulate(example_list)))

输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

从0开始:

import itertools

example_list=[1 for _ in range(10)]
print(list(itertools.accumulate(example_list,initial=0)))

输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

本文撰写过程中参考的网络资料

  1. Python中itertools.combinations()的使用_hyk今天写算法了吗的博客-CSDN博客_itertools.combination
  2. 还没看完
    1. python3迭代器iter()函数和itertools模块_Ranger L的博客-CSDN博客
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值