找到 m 长列表的所有 n 长排列(有重复),n>m

rjc*_*810 1 python algorithm combinations permutation

假设我有一些列表 [0,1,2]。然后我想返回该列表的所有 n 长“排列”。例如,如果 n=5,我应该枚举 3^5 个选择:

[0,0,0,0,0]
[0,0,0,0,1]
[0,0,0,0,2]
[0,0,0,1,0]
...
[2,2,2,2,2]
Run Code Online (Sandbox Code Playgroud)

我已经在堆栈溢出上浏览类似的帖子有一段时间了,并且尝试了 itertools 库中的许多功能,包括组合、combinations_with_repeats、排列等,但这些都不会给我我想要的输出。自己编写代码并不难,但我觉得 5 重嵌套循环在我的代码中看起来会很混乱,而且我宁愿使用另一个库中的实现(如果存在)。我想我只是在错误的地方寻找。谢谢

FMc*_*FMc 5

Python 的itertools.product将完全满足您的需求。

import sys
from itertools import product

DIGITS = (0, 1, 2)
N = int(sys.argv[1])

for tup in product(DIGITS, repeat = N):
    print(tup)
Run Code Online (Sandbox Code Playgroud)