Reputation: 1
I apologize in advance if this question has already been answered. I have done my best to search for a solution with my limited knowledge of terminology.
This is the line of code in question:
Matrix = list([s0, s1, s2] for s0 in splits[0] for s1 in splits[1] for s2 in splits[2])
Basically, I'm constructing a list (Matrix) with all permutations in the list of lists, "Splits". However, Splits is not always the same size. For instance, sometimes there are 4 columns and the line would look like this:
Matrix = list([s0, s1, s2, **s3**] for s0 in splits[0] for s1 in splits[1] for s2 in splits[2] **for s3 in splits[3]**)
How can I make this line adaptive to the length of Splits? I.e.
Matrix = list([s0,s1... , sN] for s0 in splits[0] for s1 in splits[1] ... for sN in splits[N])
Thank you
Upvotes: 0
Views: 45
Reputation: 60944
Unpack splits
into the arguments to itertools.product
:
from itertools import product
splits = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Note: a list of tuples, because product yields tuples
explicit = list((s0, s1, s2) for s0 in splits[0] for s1 in splits[1] for s2 in splits[2])
unpacking = list(product(*splits))
assert explicit == unpacking
Upvotes: 1