用于简化组合构造(如排列、组合和笛卡尔积)的递归生成器称为组合迭代器。
在Python中,有4个组合迭代器:
# 从 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)]
# 从itertools模块导入产品功能
from itertools import permutations
print ("All the permutations of the given list is:")
print (list(permutations([1, 'geeks'], 2)))
print()
print ("All the permutations of the given string is:")
print (list(permutations('AB')))
print()
print ("All the permutations of the given container is:")
print(list(permutations(range(3), 2)))
输出:
All the permutations of the given list is:
[(1, 'geeks'), ('geeks', 1)]
All the permutations of the given string is:
[('A', 'B'), ('B', 'A')]
All the permutations of the given container is:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
# 从itertools模块导入组合
from itertools import combinations
print ("All the combination of list in sorted order(without replacement) is:")
print(list(combinations(['A', 2], 2)))
print()
print ("All the combination of string in sorted order(without replacement) is:")
print(list(combinations('AB', 2)))
print()
print ("All the combination of list in sorted order(without replacement) is:")
print(list(combinations(range(2), 1)))
输出:
All the combination of list in sorted order(without replacement) is:
[('A', 2)]
All the combination of string in sorted order(without replacement) is:
[('A', 'B')]
All the combination of list in sorted order(without replacement) is:
[(0, ), (1, )]
# 从itertools模块导入组合
from itertools import combinations_with_replacement
print ("All the combination of string in sorted order(with replacement) is:")
print(list(combinations_with_replacement("AB", 2)))
print()
print ("All the combination of list in sorted order(with replacement) is:")
print(list(combinations_with_replacement([1, 2], 2)))
print()
print ("All the combination of container in sorted order(with replacement) is:")
print(list(combinations_with_replacement(range(2), 1)))
输出:
All the combination of string in sorted order(with replacement) is:
[('A', 'A'), ('A', 'B'), ('B', 'B')]
All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (2, 2)]
All the combination of container in sorted order(with replacement) is:
[(0, ), (1, )]
如果本文对你有帮助,别忘记给我个3连 ,点赞,转发,评论,
关注与私信博主(08)学习更多Python知识与技巧,课件,源码,安装包,还有最新大厂面试资料等等等
咱们下期见。
收藏 等于白嫖,点赞才是真情。