组合迭代器
用于简化组合构造(如排列、组合和笛卡尔积)的递归生成器称为组合迭代器。
在Python中,有4个组合迭代器:
- 产品(): 此工具计算输入可迭代对象的笛卡尔积。为了计算可迭代对象与自身的乘积,我们使用可选的 repeat 关键字参数来指定重复次数。此函数的输出是按排序顺序排列的元组。
例:
# 从 itertools 模块导入产品功能
from itertools import product
print("The cartesian product using repeat:")
print(list(product([1, 2], repeat = 2)))
print()
print("The cartesian product of the containers:")
print(list(product(['geeks', 'for', 'geeks'], '2')))
print()
print("The cartesian product of the containers:")
print(list(product('AB', [3, 4])))
输出:
The cartesian product using repeat:
[(1, 1), (1, 2), (2, 1), (2, 2)]
The cartesian product of the containers:
[('geeks', '2'), ('for', '2'), ('geeks', '2')]
The cartesian product of the containers:
[('A', 3), ('A', 4), ('B', 3), ('B', 4)]
- 排列(): 名称不言自明的排列()用于生成可迭代的所有可能的排列。所有元素都根据