生成 python 中所有可能的数组列组合

Generate all possible combinations of array columns in python

比如我有这样的数组

[
  [1,2,3],
  [4],
  [5,6],
]

我想生成上面列表中的所有组合,如果它应该看起来像这样的话。

[1, 4, 5]
[1, 4, 6]
[2, 4, 5]
[2, 4, 6]
[3, 4, 5]
[3, 4, 6]

给你:

a = [1,2,3]
b = [4]
c = [5,6]

d = [[x, y, z] for x in a for y in b for z in c]

听起来你想要product from the built-in itertools图书馆

>>> import itertools
>>> list(itertools.product([1, 2, 3], [4], [5, 6]))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
>>>
>>> columns = [[1,2,3],
               [4],
               [5,6]]
>>> list(itertools.product(*columns))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]

在这种情况下,要生成笛卡尔积,您只需在所有维度上进行迭代

例如:

for x in dimension_x:
    for y in dimension_y:
         for z in dimension_z:
             use the x,y,z

算法的复杂度总是很高(对于 2 个数组 -> n2,对于 3 -> n3,...,对于 M -> n^M,其中 n 是最长数组的长度)。

请注意您有重复项: (a,b) 与 (b,a) 相同。因此,如果不需要重复项,您可以更改算法以更快地工作。