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?

有帮助吗?

解决方案

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):
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top