无法使用迭代工具获取 Python 函数中的所有排列



我正在寻找以下这些数字 [1, 2, 3, 4] 和长度 3 的所有可能序列中所有可能组合的列表。我让代码工作了一半,但它没有给我所有想要的输出,例如它缺少例如组合,例如:121、132、131 等。缺少什么?

from itertools import combinations_with_replacement 
# Get all combinations of [1, 2, 3, 4] and length 3 
comb = combinations_with_replacement([1, 2, 3, 4], 3) 
# Print the obtained combinations 
for i in list(comb): 
print (i) 
OUT:
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
(1, 2, 4)
(1, 3, 3)
(1, 3, 4)
(1, 4, 4)
(2, 2, 2)
(2, 2, 3)
(2, 2, 4)
(2, 3, 3)
(2, 3, 4)
(2, 4, 4)
(3, 3, 3)
(3, 3, 4)
(3, 4, 4)
(4, 4, 4)

您似乎正在寻找所有排列。您可以使用itertools中的product

from itertools import product
a = [1,2,3,4]
list(product(*[a]*3))

最新更新