【问题标题】:Finding combinations where the length of the combination is more then the variables being used查找组合长度大于所使用变量的组合
【发布时间】:2016-05-21 14:28:01
【问题描述】:

我正在尝试从 2 个列表中获取 5 个长度组合,但找不到任何有用的东西。

x = [5,7]
abc = list(itertools.combinations((x),5))

我得到的只是[]

希望得到 [5,7] 的所有可能组合,但长度为 5,例如 [5,7,7,5,7]。

这似乎是可能的,我尝试了很多不同的东西。

再次感谢大家的帮助。

【问题讨论】:

    标签: python-2.7 math itertools


    【解决方案1】:

    你得到[] 的原因确实是(正如标题所示)你想要一个比元素数更长的长度。鉴于,the doc 说:

    itertools.combinations(iterable, r):

    从输入迭代中返回 r 个长度的子序列

    我猜你需要的是another function(文档中的下一段):

    >>> x = [5, 7]
    list(itertools.combinations_with_replacement((x),5))                        
    [(5, 5, 5, 5, 5), (5, 5, 5, 5, 7), (5, 5, 5, 7, 7), (5, 5, 7, 7, 7), (5, 7, 7, 7, 7), (7, 7, 7, 7, 7)]
    >>> 
    

    或者,正如您的示例所暗示的,您可能不想要组合而是排列?问题是,似乎不可能对组合做同样的事情。但也许cartesian product 可以解决问题?

    >>> list(itertools.product(x, repeat=5))
    [(5, 5, 5, 5, 5), (5, 5, 5, 5, 7), (5, 5, 5, 7, 5), (5, 5, 5, 7, 7), (5, 5, 7, 5, 5), (5, 5, 7, 5, 7), (5, 5, 7, 7, 5), (5, 5, 7, 7, 7), (5, 7, 5, 5, 5), (5, 7, 5, 5, 7), (5, 7, 5, 7, 5), (5, 7, 5, 7, 7), (5, 7, 7, 5, 5), (5, 7, 7, 5, 7), (5, 7, 7, 7, 5), (5, 7, 7, 7, 7), (7, 5, 5, 5, 5), (7, 5, 5, 5, 7), (7, 5, 5, 7, 5), (7, 5, 5, 7, 7), (7, 5, 7, 5, 5), (7, 5, 7, 5, 7), (7, 5, 7, 7, 5), (7, 5, 7, 7, 7), (7, 7, 5, 5, 5), (7, 7, 5, 5, 7), (7, 7, 5, 7, 5), (7, 7, 5, 7, 7), (7, 7, 7, 5, 5), (7, 7, 7, 5, 7), (7, 7, 7, 7, 5), (7, 7, 7, 7, 7)]
    

    编辑:你的问题不是真的很接近这个问题吗:python all possible combinations of 0,1 of length k

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2020-07-28
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多