Use itertools.product()
:
from itertools import product
for aa, bb, cc in product(range(limitA), range(limitB), range(limitC)):
Where limitA == limitB == limitC
this can be simplified to:
for aa, bb, cc in product(range(limitA), repeat=3):
Question
I'd like to reduce three for loops into one by generating all the iterators in one go. Basically I have a dictionary that uses tuples as its keys. I know I can do
for aa in range(limitA):
for bb in range(limitB):
for cc in range(limitC):
do_stuff(my_dict[(aa,bb,cc)])
But is there a way that requires less lines of code? Something like
for aa,bb,cc in range(limitA), range(limitB), range(limitC):
do_stuff(my_dict[(aa,bb,cc)])
This returns the error "ValueError: need more than 2 values to unpack
"
If this cannot be done generally, does the special case of limitA == limitB == limitC
have a solution?
Solution
Use itertools.product()
:
from itertools import product
for aa, bb, cc in product(range(limitA), range(limitB), range(limitC)):
Where limitA == limitB == limitC
this can be simplified to:
for aa, bb, cc in product(range(limitA), repeat=3):