简体   繁体   English

在 Python 中通过重复查找列表的所有组合

[英]Finding all combinations of a list in Python with repetition

I am looking to find and print all possible combinations of the set (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) of length 5. There should be 13 choose 5 combinations (6188) because order does NOT matter, and repetition is allowed.我正在寻找并打印长度为 5 的集合 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 的所有可能组合。应该有 13 个选择 5组合 (6188) 因为顺序无关紧要,并且允许重复。 I found this code and was using it:我找到了这段代码并正在使用它:

    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)

However, this is not printing all 6188 combinations.但是,这不会打印所有 6188 种组合。 Trying to figure out how to tweak the code so it spits out all of the combos.试图弄清楚如何调整代码,使其吐出所有组合。

What you want is to use combinations_with_replacement as @Dani Mesejo commented.您想要的是使用combinations_with_replacement正如@Dani Mesejo 评论的那样。
From the doc:从文档:

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.从输入迭代中返回元素的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM