如何生成具有 V 个可能值的 N 个插槽的所有可能组合?

How to generate all possible combinations of N slots with V possible values?

我有 N 个有序槽。每个插槽的值都在 V 个可能值内

N = 4 # number of objects (e.g. slots)
possible_values = ['A','B']
V = len(possible_values )

如何生成 Python 中所有可能组合的列表?例如,当 V=2 和 N=4 时,我想得到以下 2**4 种不同组合的列表:

combinations = [
    [ 'A', 'A', 'A', 'A' ], # combination 0
    [ 'A', 'A', 'A', 'B' ], # combination 1
    [ 'A', 'A', 'B', 'A' ], # combination 2
    [ 'A', 'A', 'B', 'B' ], # combination 3
    [ 'A', 'B', 'A', 'A' ], # combination 4
    [ 'A', 'B', 'A', 'B' ], # combination 5
    [ 'A', 'B', 'B', 'A' ], # combination 6
    [ 'A', 'B', 'B', 'B' ], # combination 7
    [ 'B', 'A', 'A', 'A' ], # combination 8
    [ 'B', 'A', 'A', 'B' ], # combination 9
    [ 'B', 'A', 'B', 'A' ], # combination 10
    [ 'B', 'A', 'B', 'B' ], # combination 11
    [ 'B', 'B', 'A', 'A' ], # combination 12
    [ 'B', 'B', 'A', 'B' ], # combination 13
    [ 'B', 'B', 'B', 'A' ], # combination 14
    [ 'B', 'B', 'B', 'B' ], # combination 15
]

我希望代码在 N 和 V 不同时工作。例如,当 N=9 个插槽和 V=4 个可能值时,我期望列表包含 4**9=262144 个可能的组合。

N = 4 # number of objects (e.g. slots)
possible_values = ['A','B']

result = itertools.product(possible_values, repeat=N)

print(list(result))