How to iterate in cascading format (in a for loop) over a list of unknown length in Python?

Consider the list A = [ [ ], [ ], ..., [ ] ] (n times). And each sub-list A contains several lists in them. What I would like to do is iterate over them at the same time. It can be easily done using the " itertools.product " function from the itertools library. Sort of

  for i,j,k in itertools.product(A[0],A[1],A[2]): #my code 

will be sufficient. However, I do not know the length of the list A. In case it is 3, I can use the code above. I'm currently 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 am coding in Python.

+5
source share
2 answers

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 values. Instead of writing i,j,k , etc. You will use ii[0],ii[1],ii[2] . If you want to make qualitatively different things with these variables, depending on how many of them exist, there is no way to get around any branching, of course. But if the only differences were to include additional variables in the same type of operation, you can probably greatly simplify the code inside your loop.

+5
source

This is normal?

 for z in itertools.product(*A): 
+1
source

Source: https://habr.com/ru/post/1238295/


All Articles