0

I have an array of arrays that looks like this:

arrays = [['a', 'b'], [1, 2], ['x', 'y', 'z']]

but could also be expanded.

I need to feed these to my_function(a_or_b, one_or_two, x_y_or_x) in all of their possible combinations (a 1 x, a 2 x, a 1 y, a 1 z, ecc). Using numpy is an option.

Though it appears as a simple problem, I have no idea where to start...

Yes, I could loop like:

for array in arrays:
    for ...

and then what? Looping through the arrays means that on my second iteration arrays[0] would no longer be first and I'd mess up the order. I also would have duplicates.

How can I do this? I don't care in which order these functions are called, but I do care that they're not called twice with the same combination and that the arguments are in order.

my_function(a, 1, x)
my_function(b, 1, x)
my_function(a, 2, x)
my_function(b, 2, x)
my_function(a, 1, y)
my_function(b, 1, y)
my_function(a, 2, y)
ecc...
1
  • Try itertools.product or one of the other very useful tools in itertools Commented Feb 21, 2019 at 1:39

1 Answer 1

4

itertools.product does exactly this. It will generate all combinations from your 3 sublists. Then you can unpack them as arguments in your function:

from itertools import product

combs = product(*arrays)
for comb in combs:
    my_function(*comb)

Calls

my_function('a', 1, 'x')
my_function('a', 1, 'y')
my_function('a', 1, 'z')
my_function('a', 2, 'x')
my_function('a', 2, 'y')
my_function('a', 2, 'z')
my_function('b', 1, 'x')
my_function('b', 1, 'y')
my_function('b', 1, 'z')
my_function('b', 2, 'x')
my_function('b', 2, 'y')
my_function('b', 2, 'z')
Sign up to request clarification or add additional context in comments.

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.