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.
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)
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