Atul
Atul

Reputation: 536

Generate all possible combinations of array columns in python

For example, I have array like this

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

I want to generate all combinations from the list above, which if it should look something like this.

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

Upvotes: 1

Views: 1730

Answers (3)

fgregg
fgregg

Reputation: 3249

Sounds like you want product from the built-in itertools library

>>> 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)]

Upvotes: 4

Dawid Dave Kosiński
Dawid Dave Kosiński

Reputation: 901

To make a Cartesian product you just need to iterate in all dimensions in this case

For example:

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

The complexity of the algorithm will always be tough (for 2 arrays -> n2, for 3 -> n3, ..., for M -> n^M where n is the length of the longest array).

Note that you have duplicates: (a,b) is the same as (b,a). So you can change the algorithm to work faster if you don't need the duplicates.

Upvotes: 0

zipa
zipa

Reputation: 27869

Here you go:

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]

Upvotes: 3

Related Questions