For my customers, iterating through mul开发者_开发知识库tiple 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
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.
精彩评论