Python Itertools

2025 年 8 月 28 日 | 阅读 9 分钟

Itertools 是 Python 3 标准库中最令人惊叹的库之一。这个库拥有许多很酷的函数,毫不夸张地说,它是 Python 编程语言的瑰宝。Python 提供了关于 itertools 的精彩文档,但在本教程中,我们将讨论几个重要且有用的 itertools 函数或迭代器。

itertools 的关键在于,这个库的函数用于编写内存效率高且精确的代码。

在学习 Python itertools 之前,你应该了解 Python 迭代器和生成器。在本文中,我们将为初学者和专业人士介绍 itertools。

引言

根据 itertools 的官方定义,“该模块实现了许多受 APL、Haskell 和 SML 构造启发的迭代器构建块”。简单来说,许多迭代器可以一起创建“迭代器代数”,从而能够完成复杂的任务。itertools 中的函数用于生成更复杂的迭代器。我们来看一个例子:Python 内置的 zip() 函数接受任意数量的可迭代对象作为参数。它迭代元组并返回它们对应的元素。

输出

[(1, 'a'), (2, 'b'), (3, 'c')]

在上面的代码中,我们将两个列表 [1,2,3] 和 ['a', 'b', 'c'] 作为可迭代对象传递给 zip() 函数这些列表一次返回一个元素。在 Python 中,实现 .__iter__().__getitem__() 方法的对象称为可迭代对象。

Python 的 iter() 函数用于在可迭代对象上调用并返回该可迭代对象的迭代器对象。

输出

<str_iterator object at 0x01505FA0>

Python 的 zip() 函数会调用其每个参数上的 iter(),然后通过将结果组合成元组来调用 next()

注意:如果你正在使用 zip() 函数和 map() 函数,这意味着你已经在使用了 itertools。你不需要单独导入它。

迭代器类型

itertools 模块中有多种类型的迭代器。列表如下

  • 无限迭代器
  • 组合迭代器
  • 终止迭代器

无限迭代器

在 Python 中,任何实现 for 循环的对象都称为迭代器。列表、元组、集合、字典、字符串都是迭代器的例子,但迭代器也可以是无限的,这种迭代器称为无限迭代器

Iterator参数结果
count(start,step)start, [step]start, start+step, step+2*step
cycle()Pp0,p1,….plast
repeat()elem [,n]elem, elem, elem,….无限次或最多 n 次
  • count(start, stop):它从起始值开始无限打印。step 参数是可选的,如果为 step 提供了值,则将跳过一定数量的步。考虑以下示例

输出

10 15 20 25 30 35 40 45
  • cycle(iterable):此迭代器按顺序打印传递参数中的所有值。它以循环方式打印值。考虑以下示例

输出

    1 2 3 1 2 3 1 2 3 1 2

示例 - 2:使用 next() 函数

输出

Java T Point Java T Point
  • repeat(val,num):顾名思义,它会无限次地重复打印传入的值。num 参数是可选的。考虑以下示例

输出

[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40]

组合迭代器:复杂的组合结构可以通过递归生成器进行简化。排列、组合和笛卡尔积是组合构造的例子。

在 Python 中,有四种组合迭代器

  • Product() - 它用于计算输入可迭代对象的笛卡尔积。在此函数中,我们使用可选的 repeat 关键字参数来计算可迭代对象与其自身的积。repeat 关键字表示重复的次数。它以排序元组的形式返回输出。考虑以下示例

输出

Computing cartesian product using repeat Keyword Argument:
[(1, 1), (1, 2), (2, 1), (2, 2)]

Computing cartesian product of the containers:
[('Java', '5'), ('T', '5'), ('point', '5')]

Computing product of the containers:
[('C', 4), ('C', 5), ('D', 4), ('D', 5)] 
  • Permutations():它用于生成可迭代对象的所有可能排列。每个元素的唯一性取决于其位置而不是值。它接受两个参数 iterablegroup_size。如果 group_size 的值为 none 或未指定,则 group_size 将变为可迭代对象的长度。

输出

Computing all permutation of the following list
[(3, 'Python'), ('Python', 3)]

Permutations of following string
[('A', 'B'), ('B', 'A')]

Permutation of the given container is:
[(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
  • Combinations():它用于按指定的组大小以排序顺序打印容器的所有可能组合(不重复)。

输出

Combination of list in sorted order(without replacement) [('B', 3)]
Combination of string in sorted order [('Z', 'X')]
Combination of list in sorted order [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
  • Combination_with_replacement():它接受两个参数,第一个参数是长度为 r 的元组,第二个参数是重复次数。它从可迭代对象的元素中返回一个长度为 n 的子序列,并重复相同的过程。在 combination_with_replacement() 中,单个元素可以重复自身

输出

Combination of string in sorted order(with replacement) is:
[('X', 'X', 'X'), ('X', 'X', 'Y'), ('X', 'Y', 'Y'), ('Y', 'Y', 'Y')]

Combination of list in sorted order(with replacement) is:
[(4, 4, 4), (4, 4, 2), (4, 2, 2), (2, 2, 2)]

Combination of container in sorted order(with replacement) is:
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]

终止迭代器

终止迭代器通常用于处理小型输入序列,并根据所用迭代器功能的函数生成输出。

有不同类型的终止迭代器

  • accumulate(iter, func):它接受两个参数,第一个参数是可迭代对象,第二个参数是在可迭代对象的每个值迭代时要执行的函数。如果函数未在 accumulate() 迭代器中定义,则默认执行加法。输出可迭代对象取决于输入可迭代对象;如果输入可迭代对象不包含任何值,则输出可迭代对象也将为空。

输出

The sum is : [1, 5, 10, 17, 26, 37]
The product is : [1, 4, 20, 140, 1260, 13860]
The sum is : [1, 5, 10, 17, 26, 37]
The product is : [1, 4, 20, 140, 1260, 13860]
  • chain(iter1, iter2) - 它用于将传递给参数的每个可迭代对象中的所有值按链式打印。考虑以下示例

输出

The output is: [1, 2, 3, 4, 1, 5, 6, 8, 9, 10, 11, 12]
  • dropwhile(func, seq) - 它仅在 func 之后开始打印字符。考虑以下参数

输出

The output is  : [5, 7, 8]
  • filterfalse(func,seq) - 我们可以从它的名字来理解它,因为这个迭代器只打印那些对传入函数返回 false 的值。考虑以下示例

输出

The Output is : [15, 27]
  • islice(iterable,start,stop,step) - 它根据给定位置对给定可迭代对象进行切片。它分别接受四个参数,即可迭代对象、容器、起始位置、结束位置和步长(可选)。

输出

The sliced list values are : [34, 73, 19]
  • starmap(func, tuple list) - 它接受两个参数;第一个参数是函数,第二个参数是包含元组形式元素的列表。考虑以下示例。

输出

The values acc. to function are : [20, 40, 90, 27]
  • takewhile(func, iterable) - 它是 dropwhile() 的反向。它将打印值,直到遇到 false 条件。考虑以下示例

输出

The list values until false value return : [20, 42, 64]
  • tee(iterator, count) - 它将容器分成参数中定义的迭代器数量。考虑以下示例

输出

(<itertools._tee object at 0x01B88D88>, <itertools._tee object at 0x01B88DA8>, <itertools._tee object at 0x01B88BA8>)
The iterators are : 
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
  • zip_longest(iterable1, iterable2, fillval) - 它按顺序交替打印可迭代对象的值。如果其中一个可迭代对象打印完所有值,则剩余的值将用分配给 fill value 的值填充。

输出

The combined value of iterables is :
('J', 'T') ('a', 'p') ('v', 'o') ('a', 'i') ('_', 'n') ('_', 't')

在本教程中,我们讨论了几种有用的迭代器以及 itertools。