【问题标题】:Finding all combinations of a list in Python with repetition在Python中查找列表的所有组合并重复
【发布时间】:2020-03-30 15:40:53
【问题描述】:

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

【问题讨论】:

  • 使用combinations_with_replacement,它给出了所有6188个组合

标签: python combinations repeat itertools combinatorics


【解决方案1】:

你想要的是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多