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



我有 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))

最新更新