1

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

3 Answers 3

4

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)]
Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.