Python 标准库之 itertools 模块

devtools/2025/3/29 17:40:36/

1. itertools 模块简介

itertools 模块是 Python 标准库中用于操作迭代器的工具集。迭代器是 Python 中一种强大的概念,允许我们逐个处理数据序列,而无需一次性将整个序列加载到内存中。itertools 模块提供了一系列函数,可用于创建、组合和处理迭代器,极大地简化了与迭代相关的编程任务,在处理大型数据集或需要复杂迭代逻辑的场景中非常有用。

2. 无穷迭代器

  • count():生成从指定值开始的无穷整数序列。
python">import itertoolscounter = itertools.count(start = 1, step = 2)
for _ in range(5):print(next(counter))

在上述代码中,itertools.count(start = 1, step = 2) 创建了一个从 1 开始,步长为 2 的无穷整数迭代器。通过 next(counter) 获取迭代器的下一个值,这里使用 for 循环获取前 5 个值,输出为 1 3 5 7 9

  • cycle():循环迭代给定的序列,无穷重复。
python">import itertoolscycles = itertools.cycle(['a', 'b', 'c'])
for _ in range(6):print(next(cycles))

此代码中,itertools.cycle(['a', 'b', 'c']) 创建了一个循环迭代 ['a', 'b', 'c'] 序列的无穷迭代器。循环 6 次,输出为 a b c a b c

  • repeat():重复生成一个元素,无穷次或指定次数。
python">import itertoolsrepeater = itertools.repeat('hello', times = 3)
for item in repeater:print(item)

这里 itertools.repeat('hello', times = 3) 创建了一个重复 'hello' 三次的迭代器,输出为 hello hello hello。如果不指定 times 参数,将无穷重复。

3. 有限迭代器

  • accumulate():对迭代器中的元素进行累积计算。
python">import itertools
import operatornums = [1, 2, 3, 4]
acc = itertools.accumulate(nums, operator.add)
print(list(acc))

代码中,itertools.accumulate(nums, operator.add) 对列表 nums 中的元素进行累加操作。operator.add 是用于指定累加操作的函数。输出为 [1, 3, 6, 10],分别是 11 + 21 + 2 + 31 + 2 + 3 + 4 的结果。如果不指定操作函数,默认进行加法运算。

  • chain():将多个迭代器连接成一个迭代器。
python">import itertoolslist1 = [1, 2]
list2 = [3, 4]
chained = itertools.chain(list1, list2)
print(list(chained))

itertools.chain(list1, list2) 将列表 list1list2 连接成一个迭代器,输出为 [1, 2, 3, 4],就像将两个列表合并成一个序列进行迭代。

4. 组合迭代器

  • product():生成多个迭代器的笛卡尔积。
python">import itertoolscolors = ['red', 'blue']
sizes = ['S', 'M']
products = itertools.product(colors, sizes)
print(list(products))

这里 itertools.product(colors, sizes) 生成了 colorssizes 两个列表的笛卡尔积,输出为 [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')],即两个列表元素所有可能的组合。

  • permutations():生成给定序列的所有排列。
python">import itertoolsnums = [1, 2, 3]
permutations_list = itertools.permutations(nums)
print(list(permutations_list))

itertools.permutations(nums) 生成列表 nums 中元素的所有排列,输出为 [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

  • combinations():生成给定序列的所有组合(不考虑顺序)。
python">import itertoolsnums = [1, 2, 3]
combinations_list = itertools.combinations(nums, 2)
print(list(combinations_list))

itertools.combinations(nums, 2) 生成列表 nums 中元素长度为 2 的所有组合,输出为 [(1, 2), (1, 3), (2, 3)],组合中的元素顺序是固定的,且不包含重复组合。


http://www.ppmy.cn/devtools/171353.html

相关文章

C# 的Lambda表达式‌常见用法和示例

C# 的 ‌Lambda 表达式‌是一种强大的语法糖,能够极大简化代码并增强灵活性。以下是它的主要功能和应用场景,结合具体示例说明: 1. ‌简化委托实例化‌ Lambda 可以快速定义委托(如 Func、Action),无需显式…

【QT】Qt creator快捷键

Qt creator可以通过以下步骤快捷键査看调用关系: 1.打开代码文件。 2.将光标放在你想要查看调用关系的函数名上。 3.按下键盘快捷键 CtrlshiftU。 4.弹出菜单中选择“调用路径”或“被调用路径” 5.在弹出的窗口中可以查看函数的调用关系 折叠或展开代码快捷键&…

Python条件处理,新手入门到精通

Python条件处理,新手入门到精通 对话实录 **小白**:(崩溃)我写了if x 1:,为什么Python会报错? **专家**:(推眼镜)**是赋值,才是比较**!想判断相…

2025最新版Ubuntu Server版本Ubuntu 24.04.2 LTS下载与安装-详细教程,细致到每一步都有说明

官网 https://ubuntu.com/ 下载 点击菜单 Prodercts> Ubuntu OS>Ubuntu Server 点击下载 下载后会有个弹窗 安装 选择第一个 install Ubuntu Server 直接默认,选择English 【默认】 选择键盘布局【默认】 选择安装配置【默认】 配置网络 我这里选择…

基于单片机的农作物自动灌溉系统

标题:基于单片机的农作物自动灌溉系统 内容:1.摘要 本研究针对传统农作物灌溉方式效率低、水资源浪费严重等问题,旨在设计一种基于单片机的农作物自动灌溉系统。采用土壤湿度传感器实时采集土壤湿度数据,将数据传输至单片机进行处理,单片机根…

本地部署Stable Diffusion生成爆火的AI图片

直接上代码 Mapping("/send") Post public Object send(Body String promptBody) { JSONObject postSend new JSONObject(); System.out.println(promptBody); JSONObject body JSONObject.parseObject(promptBody); List<S…

deepseek实战教程-第六篇查找源码之仓库地址与deepseek-R1、deepseek-LLM仓库内容查看

上一篇讲了支持deepseek的模型应用的本地安装和部署以及使用。再上一篇讲解了deepseek提供的开放api,便于开发者基于deepseek提供的接口来编写属于自己的业务应用程序。但是前面几篇我们都是在用模型,我们知道deepseek是开源的,那么deepseek的源码在哪里,具体源码是什么样的…

2.Excel :快速填充和拆分重组

一 案例1&#xff1a;快速填充 电子邮件中包含每个人的人名&#xff0c;现在要提取电子邮件中的姓名到名字列。 方法1&#xff1a;将 Nancy 复制到单元格后&#xff0c;邮件会高亮&#xff0c;然后输入A的时候系统就会知道提取名字了。 补充&#xff1a;如果第三个位置输入错误…