Python: nested counters

For my clients, repeating with multiple counters turns into a repetitive task.

The easiest way is something like this:

cntr1 = range(0,2) cntr2 = range(0,5) cntr3 = range(0,7) for li in cntr1: for lj in cntr2: for lk in cntr3: print li, lj, lk 

The number of counters can be from 3 to 3, and those that are nested in loops begin to occupy real estate.

Is there a way for Pythonic to do something like this?

 for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3): print li, lj, lk 

I keep thinking that something in itertools will fit this bill, but I'm just not familiar with itertools enough to understand the options. Is there a solution like itertools, or do I need to roll it?

Thanks J

+6
python iteration
source share
1 answer

Do you want itertools.product

 for li, lj, lk in itertools.product(cntr1, cntr2, cntr3): print li, lj, lk 

Will do what you request. The name follows from the concept of a Cartesian product.

+7
source share

All Articles