Skip to content
Advertisement

All possible combinations of arrays in python

I have a problem finding all combinations of a 2D array. Let’s suggest I have an array as follwoing:

JavaScript

Now I need to get all possible combninations such as

JavaScript

I’ve managed to get it with numpy and meshgrids with single arrays:

JavaScript

But with a 2D array I cant’t get it to work.

JavaScript

This doesn’t give me the expected result but only:

JavaScript

Is there any way to get this working correctly?

Advertisement

Answer

You can use the itertools package in the standard library. itertools.product generates all combinations that you wish.

JavaScript

If you prefer lists to tuples, you can do the following:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement