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

时间:2018-07-05 18:51:46

标签: python base

我有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个可能的组合。

1 个答案:

答案 0 :(得分:-1)

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

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

print(list(result))