如何生成具有V个可能值的N个时隙的所有可能组合? [英] How to generate all possible combinations of N slots with V possible values?

查看:88
本文介绍了如何生成具有V个可能值的N个时隙的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有N个有序插槽.每个广告位的值均在V个可能的值之内

I have N ordered slots. Each slot has a value within V possible values

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

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

How would it be possible to generate the list of all possible combinations in Python? For instance, when V=2 and N=4, I would like to get the following list of the 2**4 different combinations:

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个可能的组合.

I would like the code to work when N and V vary. For example, when N=9 slots and V=4 possible values, I expect the list of the 4**9=262144 possible combinations.

推荐答案

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

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

print(list(result))

这篇关于如何生成具有V个可能值的N个时隙的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆