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?
source to share
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]
source to share