Iterating over all possible combinations of list items and using them as indexes in Python

I have the following list:

indices = [125,144,192]

      

I want to create a structure such that I want to use any combination of these three numbers as indices for a 3D list:

myList[i][j][k] = someVar

      

where i

, j

and k

cover all combinations shown below:

i,j,k = 0,0,0
i,j,k = 0,0,192
i,j,k = 0,144,0
i,j,k = 125,0,0
i,j,k = 0,144,192
i,j,k = 125,0,192
i,j,k = 125,144,0
i,j,k = 125,144,192

      

In other words, I would like to simplify the following:

for i in [0,125]:
    for j in  [0,144]:
        for k in [0,192]:
            myList[i][j][k] = someVar 

      

What would be the pythonic way to do this?

+3


source to share


2 answers


You can use itertools.product

:

>>> list(product([0,125],[0,144],[0,192]))
[(0, 0, 0), 
 (0, 0, 192), 
 (0, 144, 0), 
 (0, 144, 192), 
 (125, 0, 0), 
 (125, 0, 192), 
 (125, 144, 0), 
 (125, 144, 192)]

      

Or as a more general solution, you can use izip

(in python 3 zip

is efficient) and repeat

to create wish pairs and then pass them to product

:



>>> indices = [125,144,192]
>>> from itertools import product,izip,repeat
>>> list(product(*izip(repeat(0,len(indices)),indices)))
[(0, 0, 0), (0, 0, 192), (0, 144, 0), (0, 144, 192), (125, 0, 0), (125, 0, 192), (125, 144, 0), (125, 144, 192)]
>>> 

      

And for indexing, you can do:

for i,j,k in product(*izip(repeat(0,len(indices)),indices)):
    # do stuff with myList[i][j][k]

      

+4


source


Seems more ambiguous, but ...



for triple in [(x,y,z) for x in [0,125] for y in [0,144] for z in [0,192]]:
    myList[ triple[0] ][ triple[1] ][ triple[2] ] = somevar

      

+1


source







All Articles