Reputation: 10564
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...
Upvotes: 0
Views: 49
Reputation: 10580
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')
Upvotes: 4