0%

Python/Python itertools模块

说明:

Python内置的itertools模块中包含了一系列用来产生不同款类型迭代器的函数和类,这些函数的返回值都是一个迭代器。

迭代器函数类型

无限迭代器:生成一个无限序列,比如自然序列1,2,3,4…;

有限迭代器:接受一个或多个序列作为参数,进行组合、分组和过滤

组合生成器:序列的排列、组合,求序列的笛卡尔积等

无限迭代器

组合生成器

product: product用于求多个可迭代对象的组合,它跟嵌套的for循环等价。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
j = 0
for i in itertools.product("12345","ABCDE"):
print(i,end='')
j = j+1


print("")
print("一共有{}种组合".format(j))

"""
输出结果为:
('1', 'A')('1', 'B')('1', 'C')('1', 'D')('1', 'E')('2', 'A')('2', 'B')('2', 'C')('2', 'D')('2', 'E')('3', 'A')('3', 'B')('3', 'C')('3', 'D')('3', 'E')('4', 'A')('4', 'B')('4', 'C')('4', 'D')('4', 'E')('5', 'A')('5', 'B')('5', 'C')('5', 'D')('5', 'E')
一共有25种组合

"""

permutations: 用于生成一个全排列

1
2
3
4
5
6
nums = [1,2,3,4]
print(list(itertools.permutations(nums)))

"""输出结果:
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
"""

combinations:用于求序列的组合

1
2
3
4
5
6
7
nums = [1,2,3,4]
print(list(itertools.combinations(nums,2)))
"""
输出结果:

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

⚠️注意区分product、permutations和combinations的区别