如何创建多个数组的所有可能枚举

How to create all possible enumerations of multiple arrays

我认为这在某种程度上是一个组合数学问题,但我已经很久没有这样做了,以至于我很生疏。我有一个动态数量的数组,每个数组都有一个动态数量的元素。我试图获得每个数组中所有项目的唯一组合。 例如,如果我有 3 个数组

['a','b','c']
['d',e']
['f','g']

那么我希望得到

['a','d','f'],
['a','e','f'],
['a','d','g'],
['a','e','g'],
['b','d','f'],
['b','e','f'],
['b','d','g'],
['b','e','g'],
['c','d','f'],
['c','e','f'],
['c','d','g'],
['c','e','g']

动态编写代码真的很费力,因为数组的数量和每个数组中的元素数量无法提前知道。

使用Python,我们可以通过多种方式实现这一点,

a = ['a','b','c']
b = ['d','e']
c = ['f','g']
  1. 使用多个 FOR 循环

     for i in a:
         for j in b:
             for k in c:
                 print([i, j, k])
    

输出:

['a', 'd', 'f']
['a', 'd', 'g']
['a', 'e', 'f']
['a', 'e', 'g']
['b', 'd', 'f']
['b', 'd', 'g']
['b', 'e', 'f']
['b', 'e', 'g']
['c', 'd', 'f']
['c', 'd', 'g']
['c', 'e', 'f']
['c', 'e', 'g']
  1. 使用列表解析:

     d = [[i, j, k] for i in a for j in b for k in c]
     d
    

** 输出:**

[['a', 'd', 'f'],
 ['a', 'd', 'g'],
 ['a', 'e', 'f'],
 ['a', 'e', 'g'],
 ['b', 'd', 'f'],
 ['b', 'd', 'g'],
 ['b', 'e', 'f'],
 ['b', 'e', 'g'],
 ['c', 'd', 'f'],
 ['c', 'd', 'g'],
 ['c', 'e', 'f'],
 ['c', 'e', 'g']]

我们还可以使用 itertools 模块来生成排列组合。

我认为你的问题可以用递归算法解决:

输入: arrs(数组的数组)

输出: 梳子(所有可能组合的数组)

arrs = ??? # this variable provide input arrays, like [[1,2,3], [4,5]]
combs = [] # this variable store the answer 
def get_combs(arrs, i, currentComb):
    if i >= len(arrs):
        combs.append(list(currentComb))
        return
    for elem in arrs[i]:
        currentComb.append(elem)
        get_combs(arrs, i+1, currentComb)
        currentComb.pop()

get_combs(arrs, 0, []) // after this call, the combs get the desired answer.

上面的代码在 Python 中并且很脏。