Iterate over all possible combinations of list elements and use as indices in Python -


i have following list:

indices = [125,144,192] 

i want generate such structure want use combination of 3 of these numbers indices 3d list:

mylist[i][j][k] = somevar 

where i,j, , k loop on of 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'd simplify following:

for in [0,125]:     j in  [0,144]:         k in [0,192]:             mylist[i][j][k] = somevar  

what pythonic way this?

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 more general solution can use izip (in python 3 zip efficient ) , repeat create desire pairs , pass them product :

>>> indices = [125,144,192] >>> 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 indexing can :

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

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -