迭代列表元素的所有可能组合,并在Python中用作索引

时间:2015-07-22 15:16:44

标签: python

我有以下列表:

indices = [125,144,192]

我想生成这样一种结构,我想使用这些数字中的三个的任意组合作为3d列表的索引:

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

其中ijk循环显示以下所有组合:

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

换句话说,我想简化以下内容:

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

这样做的pythonic方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以使用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)]

或者作为更通用的解决方案,您可以使用izip(在python 3 zip中效率很高)和repeat来创建愿望对,然后将其传递给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)]
>>> 

对于索引,你可以这样做:

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

答案 1 :(得分:1)

似乎更暧昧但......

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