Decomposing the problem
Suppose X = [x_1,x_2,...,x_n], Y = [y_1,y_2,...,x_m] and Z=[z_1,z_2,...,z_nm], you want to:
- pair every X with every Y, first varying Y
- then pair the resulting sequence with Z, one by one, on the order they appear.
Cartesian product of X and Y
Pairing X and Y can be done using the product method from itertools, as in:
from itertools import product
X=[1,2]
Y=[3,4,5]
print(list(product(X,Y)))
This will return [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
The itertools library doesn't return a list, but an iterable, so we can compose these iterables.
Pairing XY with Z
Now we have XY = [(x1,y_1), (x1,y_2), ... (x_1,y_m), (x_2, y_1), (x_2, y_2), ... , (x_2, y_m), ..., (x_n,y_m)] with n*m elements, and we want to pair them, respectively to Z=[z_1,z_2, ..., z_nm], to do that we can use a builtin function called zip which will pair them.
from itertools import product
X=[1,2]
Y=[3,4,5]
Z="abcdef"
XY=product(X,Y)
print(list(zip(XY, Z)))
Fixing the form
The last code will return [((1, 3), 'a'), ((1, 4), 'b'), ((1, 5), 'c'), ((2, 3), 'd'), ((2, 4), 'e'), ((2, 5), 'f')]. There is a slight deviation in the form: entries are on the form ((x,y),z) instead of [x,y,z], but we can fix that using a list comprehension:
from itertools import product
X=[1,2]
Y=[3,4,5]
Z="abcdef"
print([[x,y,z] for (x,y), z in zip(product(X,Y), Z)])
[[a1 b1] [a2 b2] ... [a5 b5]]. In my case, I want to pair each x with each y. Also, my data actually much larger than 2 x and 2 y