Section 53.1: Itertools 模块中的组合方法

itertools.combinations 将返回一个列表的 k 组合序列的生成器。

换句话说: 它将返回输入列表所有可能的 k 种组合的生成器。

例如:

如果有一个列表

a = [1,2,3,4,5]
b = list(itertools.combinations(a, 2))
print(b)

输出:

[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

Itertools 模块中的组合方法

上述输出是将生成器转换为输入列表 a 的所有可能 "成对" 组合的元组列表

您还可以找到所有的 3 个数字的组合:

a = [1,2,3,4,5]
b = list(itertools.combinations(a, 3))
print(b)

输出:

[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4),
(1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5),
(2, 4, 5), (3, 4, 5)]

Itertools 模块中的组合方法

Section 53.2: itertools.dropwhile

itertools.dropwhile 可以让你在某个条件首次变为 False 后,从序列中提取项目。

def is_even(x):
  return x % 2 == 0

lst = [0, 2, 4, 12, 18, 13, 14, 22, 23, 44]
result = list(itertools.dropwhile(is_even, lst))

print(result)

输出结果为

[13, 14, 22, 23, 44]

itertools.dropwhile

(此示例与 takewhile 的示例相同,但使用了 dropwhile)。

请注意,违反谓词(即:返回布尔值的函数)is_even 的第一个数字是 13。在此之前的所有元素都会被丢弃。

dropwhile 产生的输出结果与下面代码产生的输出结果类似。

def dropwhile(predicate, iterable):
  iterable = iter(iterable)
  for x in iterable:
    if not predicate(x):
      yield x
      break
  for x in iterable:
    yield x

将 takewhile 和 dropwhile 产生的结果连接起来,就产生了原始的可迭代程序。

result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))

itertools.dropwhile

Section 53.3: 对两个迭代器进行扫频,直到两个迭代器都耗尽为止

类似于内置函数 zip(),itertools.zip_longest 会在两个迭代表中较短的一个结束后继续迭代。

from itertools import zip_longest
a = [i for i in range(5)] # Length is 5
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # Length is 7
for i in zip_longest(a, b):
  x, y = i # Note that zip longest returns the values as a tuple
  print(x, y)

对两个迭代器进行扫频,直到两个迭代器都耗尽为止

可以像这样传递一个可选的 fillvalue 参数(默认值为 ''):

for i in zip_longest(a, b, fillvalue='Hogwash!'):
  x, y = i # Note that zip longest returns the values as a tuple
  print(x, y)

对两个迭代器进行扫频,直到两个迭代器都耗尽为止

在 Python 2.6 和 2.7 中,这个函数叫做 itertools.izip_longest。

Section 53.4: 对生成器进行切片

itertools 的 islice 功能可以对生成器进行切片:

results = fetch_paged_results() # returns a generator
limit = 20 # Only want the first 20 results
for data in itertools.islice(results, limit):
  print(data)

通常情况下,您不能对生成器进行切片:

def gen():
  n = 0
  while n < 20:
    n += 1
    yield n

for part in gen()[:3]:
  print(part)

将得到

Traceback (most recent call last):
  File "gen.py", line 6, in <module>
    for part in gen()[:3]:
TypeError: 'generator' object is not subscriptable

对生成器进行切片

不过,这样做还是行得通的:

import itertools

def gen():
  n = 0
  while n < 20:
    n += 1
    yield n

for part in itertools.islice(gen(), 3):
  print(part)

对生成器进行切片

请注意,与普通切片一样,您也可以使用 start、end 和 step 参数:

itertools.islice(iterable, 1, 30, 3)

Section 53.5: 使用函数对可迭代对象中的项目进行分组

从需要分组的可迭代程序开始

lst = [("a", 5, 6), ("b", 2, 4), ("a", 2, 5), ("c", 2, 6)]

生成分组生成器,按每个元组中的第二个元素分组:

def testGroupBy(lst):
  groups = itertools.groupby(lst, key=lambda x: x[1])
  for key, group in groups:
    print(key, list(group))

testGroupBy(lst)

# 5 [('a', 5, 6)]
# 2 [('b', 2, 4), ('a', 2, 5), ('c', 2, 6)]

使用函数对可迭代对象中的项目进行分组

只对连续元素分组。在调用 groupby 之前,您可能需要按相同的键进行排序 例如:(最后一个元素已更改)

lst = [("a", 5, 6), ("b", 2, 4), ("a", 2, 5), ("c", 5, 6)]
testGroupBy(lst)

# 5 [('a', 5, 6)]
# 2 [('b', 2, 4), ('a', 2, 5)]
# 5 [('c', 5, 6)]

使用函数对可迭代对象中的项目进行分组

groupby 返回的分组是一个迭代器,在下一次迭代之前就会失效。例如,如果想按键排序,下面的方法将不起作用。下面的组 5 是空的,因为当获取组 2 时,组 5 无效

lst = [("a", 5, 6), ("b", 2, 4), ("a", 2, 5), ("c", 2, 6)]
groups = itertools.groupby(lst, key=lambda x: x[1])
for key, group in sorted(groups):
  print(key, list(group))

# 2 [('c', 2, 6)]
# 5 []

使用函数对可迭代对象中的项目进行分组

要正确进行排序,请在排序前用迭代器创建一个列表

groups = itertools.groupby(lst, key=lambda x: x[1])
for key, group in sorted((key, list(group)) for key, group in groups):
  print(key, list(group))

# 2 [('b', 2, 4), ('a', 2, 5), ('c', 2, 6)]
# 5 [('a', 5, 6)]

Section 53.6: itertools.takewhile

itertools.takewhile 使您能够从序列中获取项目,直到某个条件首先变为 False。

def is_even(x):
return x % 2 == 0
lst = [0, 2, 4, 12, 18, 13, 14, 22, 23, 44]
result = list(itertools.takewhile(is_even, lst))
print(result)

itertools.takewhile

这将输出[0, 2, 4, 12, 18]。

请注意,违反谓词(即:返回布尔值的函数)is_even 的第一个数字是 13。一旦 takewhile 遇到对给定谓词产生 False 的值,它就会中断。

takewhile 产生的输出类似于下面代码产生的输出。s

def takewhile(predicate, iterable):
  for x in iterable:
    if predicate(x):
      yield x
    else:
      break

注:将 takewhile 和 dropwhile 产生的结果连接起来,就是原始的可迭代程序。

result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))

Section 53.7: itertools.permutations

itertools.permutations 返回迭代器中元素的连续 r 长度排列的生成器。

a = [1,2,3]
list(itertools.permutations(a))
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

list(itertools.permutations(a, 2))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

如果列表 a 有重复元素,那么产生的排列组合也会有重复元素,您可以使用 set 来获得唯一的排列组合:

a = [1,2,1]
list(itertools.permutations(a))
# [(1, 2, 1), (1, 1, 2), (2, 1, 1), (2, 1, 1), (1, 1, 2), (1, 2, 1)]

set(itertools.permutations(a))
# {(1, 1, 2), (1, 2, 1), (2, 1, 1)}

itertools.permutations

Section 53.8: itertools.repeat

重复 n 次:

>>>> import itertools
>>> for i in itertools.repeat('over-and-over', 3):
...     print(i)

over-and-over
over-and-over
over-and-over

itertools.repeat

Section 53.9: 获取迭代器中数字的累加和

accumulate 生成数字的累积和(或积)。

Python 3.x Version ≥ 3.2

>>> import itertools as it
>>> import operator

>>> list(it.accumulate([1,2,3,4,5]))
[1, 3, 6, 10, 15]

>>> list(it.accumulate([1,2,3,4,5], func=operator.mul))
[1, 2, 6, 24, 120]

获取迭代器中数字的累加和

Section 53.10: 在迭代器中循环浏览元素

cycle 是一个无限迭代器。

>>> import itertools as it
>>> it.cycle('ABCD')
A B C D A B C D A B C D ...

因此,使用时应注意给出边界,以避免出现无限循环。举例说明

>>> # Iterate over each element in cycle for a fixed range
>>> cycle_iterator = it.cycle('abc123')
>>> [next(cycle_iterator) for i in range(0, 10)]
['a', 'b', 'c', '1', '2', '3', 'a', 'b', 'c', '1']

在迭代器中循环浏览元素

Section 53.11: itertools.product

该函数可让您遍历可遍历列表的笛卡尔乘积。

例如

for x, y in itertools.product(range(10), range(10)):
  print(x, y, end=' ; ')

itertools.product

相当于

for x in range(10):
  for y in range(10):
    print(x, y, end=' ; ')

itertools.product

与所有接受可变参数的 python 函数一样,我们可以使用 * 操作符将一个列表传递给 itertools.product 进行解包。

因此

its = [range(10)] * 2
for x,y in itertools.product(*its):
  print(x, y, end=' ; ')

itertools.product

产生的结果与前面两个例子相同。

>>> from itertools import product
>>> a=[1,2,3,4]
>>> b=['a','b','c']
>>> product(a,b)
<itertools.product object at 0x0000000002712F78>
>>> for i in product(a,b):
...     print(i)
...
(1, 'a')
(1, 'b')
(1, 'c')
(2, 'a')
(2, 'b')
(2, 'c')
(3, 'a')
(3, 'b')
(3, 'c')
(4, 'a')
(4, 'b')
(4, 'c')

itertools.product

Section 53.12: itertools.count

简介:

这个简单的函数可以生成无穷级数。例如...

for number in itertools.count():
  if number > 20:
    break
  print(number)

请注意,我们必须手动中断,否则将永远打印!

输出:

0
1
2
3
4
5
6
7
8
9
10

itertools.count

参数:

count()需要两个参数:start和step`:

for number in itertools.count(start=10, step=4):
  print(number)
  if number > 20:
    break

输出:

10
14
18
22

itertools.count

Section 53.13: 将多个迭代器连锁在一起

使用 itertools.chain 创建一个生成器,该生成器将依次生成多个生成器的值。

from itertools import chain
a = (x for x in ['1', '2', '3', '4'])
b = (x for x in ['x', 'y', 'z'])
' '.join(chain(a, b))

结果是

'1 2 3 4 x y z'

将多个迭代器连锁在一起

作为另一种构造函数,可以使用类方法 chain.from_iterable ,它的单个参数是一个 iterables 的 iterable。要得到与上述相同的结果

' '.join(chain.from_iterable([a,b]))

虽然 chain 可以接受任意数量的参数,但只有 chain.from_iterable 才能将无限多的迭代表链起来。