Consider there is a list A = [ [ ], [ ], ..., [ ] ]
(n times). And each sub-list of A contains several lists in them. What I would like to do is iterate over them simultaneously. It can easily be done using "itertools.product
" function from the itertools library. Something like
for i,j,k in itertools.product(A[0],A[1],A[2]):
#my code
will suffice. However I don't know the length of list A. In case it is 3 I can use the above code. Currently I'm doing something like this
if len(A) == 2:
for i,j in itertools.product(A[0],A[1]):
#my code
elif len(A) == 3:
for i,j,k in itertools.product(A[0],A[1],A[2]):
#same code with minor changes to include parameter k
elif len(A) == 4:
for i,j,k,l in itertools.product(A[0],A[1],A[2],A[3]):
#same code with minor changes to include parameter k and l
Since this is tedious, I wanted to know if there is a generalized solution using list comprehension or something else. I'm coding in Python.
You can use *
-unpacking:
>>> A = [[1,2],[3,4]]
>>> for ii in itertools.product(*A):
... print(ii)
...
(1, 3)
(1, 4)
(2, 3)
(2, 4)
ii
will be a tuple of the values. Instead of writing i,j,k
, etc, you'll use ii[0],ii[1],ii[2]
. If you want qualitatively different things to be done with these variables depending on how many of them there are, there's no way to get around some kind of branching, of course. But if the only differences were to incorporate the extra variables in the same kind of operations, you can probably simplify the code inside your loop considerably.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With