从数字集 N 生成长度 k 的组合,顺序很重要,允许更换

Generate combinations of length k from number set N, order matters, replacement allowed

我想从一组 N 个数字生成长度为 k 的组合,其中顺序很重要,数字可以替换。例如,如果 k = 3,并且 N = [1, 2, 3],那么候选输出将包括,例如,(1, 1, 1), (2, 2, 2), (3, 2, 1) , (1, 2, 3).

我相信我已经接近完成以下代码

x = list(itertools.combinations_with_replacement(range(1,4),3)

但这给出了顺序无关紧要的结果 - 即它认为 (1, 2, 3) 与 (3, 2, 1), (2, 3, 1) 等相同

非常感谢任何帮助!

试试这个:

import itertools
x = [1, 2, 3]
list(itertools.product(x, repeat=3))

你需要的是product

import itertools

N = [1, 2, 3]

y = list(itertools.product(N, N))
print(y)  # [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
          #             ^               ^
          #             |_______________| he no longer thinks it's the same

现在,从你的问题来看,如果 k != len(N),你想做什么还不清楚,所以我会把它留给你(切片 N 也许?)..