查找组合长度大于所使用变量的组合

Finding combinations where the length of the combination is more then the variables being used

我试图从 2 种长度组合中找出 5 种长度组合,找不到任何有效的组合。

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

我得到的只有[]

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

这似乎是可能的,我已经尝试了很多不同的事情。

再次感谢大家的帮助。

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

itertools.combinations(iterable, r):

Return r length subsequences of elements from the input iterable.

我猜你需要的是 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