使用重复查找Python中列表的所有组合

问题描述 投票:0回答:2

我正在寻找并打印长度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组合。试图弄清楚如何调整代码,使其吐出所有组合。

python combinations repeat itertools combinatorics
2个回答
0
投票

如果您正在寻找组合,则应该有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)

0
投票

您想要使用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
© www.soinside.com 2019 - 2024. All rights reserved.