0

You can use itertools.product() to replace nested FOR loops if they are not interconnected.

for x, y in product(range(20), range(17)): ....

The question is there a way to do the same for hierarchical nested FOR loop ..f.e. lets say I have list-of-list :

for level2 in LoL :
  for level3 in level2 :
    for level4 in level3 :
       .....
         t1, t2,..,tn = levelM

The LoL structure could be something like this, just an example :

[[[1, 9], [1, 6], [1, 8], [1, 6], [1, 2]],
 [[5, 8], [5, 11], [5, 14], [5, 6], [5, 11]],
 [[7, 12], [7, 13], [7, 10], [7, 9], [7, 12]],
 [[22, 25], [22, 30], [22, 25], [22, 26], [22, 26]],
 [[55, 57], [55, 55], [55, 55], [55, 56], [55, 61]]]

the output does not matter, I was wondering if there is shortcut function/structure like the product()

The only other way I see is recursion, but this is more complex.

the product() hides the structure ... now that @RaySteam said it .. probably would be function that flattens it !!! up to the last level, so it returns list of tuples, because that is what you normally do in a normal scenario ...i.e. does something with the data..in a loop manner

sten
  • 7,028
  • 9
  • 41
  • 63

1 Answers1

0

Nesting for loops is a way of hiding the application of "flatten" to a multilevel data structure, therefore a shortcut of this pattern is to operate on the result of the flattened list.

The point is Python currently (probably in the future too) lacks a flatten function for arbitrarily nested lists. More information in this thread and this post.

Additionally, you don't want your structure to be fully flattened as you want to work on the innermost pairs.

Here is some code I've made for this particular use case:

from itertools import chain

# Flattens i times.
# You need to know how much you need to flatten
# Assumes that nesting level doesn't vary.
def almost_flat(lol, i):
  x = lol
  for _ in range(i):
    x = chain.from_iterable(x)
  return x

# Flattens until it obtains a list-of-lists
# Also relies on fixed nesting structure.
# implemented recursively although you may unroll it in tail recursive manner.
def flat(ls):
  if not isinstance(ls[0][0], list, tuple):
    return ls
  else:
    out = []
    for x in ls:
     out.extend(x)
    return flat(out)
Happy-Monad
  • 1,962
  • 1
  • 6
  • 13