itertools模块(一)

517 阅读2分钟

itertools模块是python内置的迭代器模块,主要用于迭代器的定制。现在对其主要功能整理如下:

1.无限迭代器

1.1 count函数

itertools.count(start=0, step=1):

生成一个迭代器,该迭代器从start开始迭代,第n次迭代返回start + n * step

eg:生成1-9之内的奇数

import itertools
​
​
for i in itertools.count(1, 2):
    if i > 9:
        break
    print(i)

result:

1
3
5
7
9

1.2 cycle函数

cycle(iterable)

把iterable变成一个可以无限循环迭代的迭代器,让iter不再只能迭代一轮。下面举例进行说明。

普通迭代器的情形

eg:

for i in a:
    if j == 5:
        break
    print(i)
    j += 1
print(f'j的值为==={j}')

result:

1
2
3
j的值为===3

由于普通迭代器只能迭代一次,所以j的值最终为3。

使用cycle函数后的情形:

from itertools import cycle
list1 = [1, 2, 3]
b = cycle(list1)
j = 0
for i in b:
    if j == 5:
        break
    print(i)
    j += 1
print(f'j的值为==={j}')

result:

1
2
3
1
2
j的值为===5

此时迭代器进行了多次迭代,遇到了break语句退出,所以此时j的值为5

1.3 repeat函数

repeat(object, ,times=None):

object:一个对象用于重复

times:重复次数,为None表示可以重复无数次

生成一个重复times次数的object的迭代器

from itertools import repeat
list1 = [1, 2, 3]
​
for num in repeat(list1, 5):
    print(num)

result:

[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

2.排列组合迭代器

2.1 product函数

product(*iterables, repeat):

iterables:需要进行笛卡尔积运算的迭代器

repeat:iterables重复次数,默认不重复

将所有iterables重复repeat遍后再进行笛卡尔积运算,默认不重复

2.1.1 不重复的情形

from itertools import product
​
for i in product('abc'):
    print(i)

result:

('a',)
('b',)
('c',)
from itertools import product
​
for i in product('abc', '12'):
    print(i)

result:

('a', '1')
('a', '2')
('b', '1')
('b', '2')
('c', '1')
('c', '2')

2.1.2 重复的情形

from itertools import product
​
for i in product('abc', repeat=3):
    print(i)

result:

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'a')
('a', 'c', 'b')
('a', 'c', 'c')
('b', 'a', 'a')
('b', 'a', 'b')
('b', 'a', 'c')
('b', 'b', 'a')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'a')
('b', 'c', 'b')
('b', 'c', 'c')
('c', 'a', 'a')
('c', 'a', 'b')
('c', 'a', 'c')
('c', 'b', 'a')
('c', 'b', 'b')
('c', 'b', 'c')
('c', 'c', 'a')
('c', 'c', 'b')
('c', 'c', 'c')

2.2 permutations函数

数学中的排列运算

from itertools import permutations
​
for i in permutations('abc', 3):
    print(i)

result:

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

2.3 combinations函数

数学中的组合运算

from itertools import combinations
​
for i in combinations('abc', 3):
    print(i)

result:

('a', 'b', 'c')

2.4 combinations_with_replacement函数

数学中的可放回抽取(前面的排列组合都是不可放回抽取)

from itertools import combinations_with_replacement
​
for i in combinations_with_replacement('abc', 3):
    print(i)

result:

('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')