我正在寻找并打印长度5的集合(0、1、2、3、4、5、6、7、8、9、10、11、12)的所有可能组合,应该是13选择5个组合(6188),因为顺序无关紧要,并且允许重复。我找到了此代码并正在使用它:
from itertools import product
for item in product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
repeat=5):
print(item)
但是,这不能打印所有6188组合。试图弄清楚如何调整代码,使其吐出所有组合。
如果您正在寻找组合,则应该有13 C 5 = 1287组合。在这种情况下,您可以使用,
itertools.combinations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5)
如果您正在寻找排列,那么应该有13 P 5 = 154440排列。在这种情况下,您可以使用,
itertools.permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5)
您想要使用combinations_with_replacement
,如@Dani Mesejo所评论。从文档:
从可迭代输入返回元素的r长度子序列允许单个元素重复多次。
from itertools import combinations_with_replacement
l = list(combinations_with_replacement([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))
print(len(l)) # 6188