用重复查找Python中列表的所有组合 [英] Finding all combinations of a list in Python with repetition

查看:52
本文介绍了用重复查找Python中列表的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找并打印长度5的集合(0、1、2、3、4、5、6、7、8、9、10、11、12)的所有可能组合.应该有13选择5个组合(6188),因为顺序无关紧要,并且允许重复.我找到了这段代码并正在使用它:

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. 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)

但是,这不能打印所有6188个组合.试图弄清楚如何调整代码,使其吐出所有组合.

However, this is not printing all 6188 combinations. Trying to figure out how to tweak the code so it spits out all of the combos.

推荐答案

您要使用的是@Dani Mesejo评论的combinations_with_replacement.
来自文档:

What you want is to use combinations_with_replacement as @Dani Mesejo commented.
From the doc:

从可迭代输入中返回元素的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

这篇关于用重复查找Python中列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆