Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nesting to a dynamic depth in Python

I have a problem I'm trying to solve which requires nesting as many levels deep as there are items in a list. Or to be precise, iterables in a list.

def example(arg_list):
for i in arg_list[0]:
    for j in arg_list[1]:
        for k in arg_list[2]:
            print "{} {} {}".format(i,j,k)

The above function would run fine as long as the "arg_list" is a list containing 3 iterables, such as [[1,3,4],[4,5,6], [9,3,2,1,0]]. If there were always four iterables in the list, that would be easy to do as well. I need to figure out how to create a function that will add another nested level for each iterable added to the "arg_list" parameter. It seems that recursion might be the way to go, but haven't been able to figure that out.

like image 903
Jashua Avatar asked Mar 13 '23 20:03

Jashua


1 Answers

What you are looking for is called a Cartesian product. Python's itertools module has a function that will do that for you.

from itertools import product

def example(arg_list):
    for items in product(*arg_list):
        print " ".join(str(item) for item in items)
like image 157
kindall Avatar answered Mar 23 '23 21:03

kindall