Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Nesting counters

For my customers, iterating through multiple counters is turning into a recurring task.

The most straightforward way would be 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 anywhere from 3 on up and those nested for loops start taking up real estate.

Is there a Pythonic way 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 would fit this bill, but I'm just not familiar enough with itertools to make sense of the options. Is there already a solution such as itertools, or do I need to roll my own?

Thanks, j

like image 751
JS. Avatar asked Nov 11 '10 00:11

JS.


1 Answers

What you want is itertools.product

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

Will do exactly what you are requesting. The name derives from the concept of a Cartesian product.

like image 150
Winston Ewert Avatar answered Oct 17 '22 01:10

Winston Ewert