有效迭代多维索引列表表示(任意维度)

2024-03-28 08:21:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我处理任意维的多维结构。我有一个xrange迭代器的Python列表,每个迭代器代表多维数组的一个索引:

indices = [ i, j, k ]

在哪里

^{pr2}$

为了生成所有可能的值,我使用以下朴素的递归代码:

def travtree(index,depth):
    "Recursion through index list"
    if depth >= len(indices):
        # Stopping Condition
        print index
    else:
        # Recursion
        currindexrange = indices[depth]
        for currindex in xrange(len(currindexrange)):
            newindex = list(index) # list copy
            newindex.append(currindexrange[currindex])
            travtree(newindex,depth+1)

travtree([],0)

这很好,但我想知道,有没有更有效的,Python式的方法?我试着在itertools模块中查找,但没有什么东西能跳出来。


Tags: 列表indexlen代表数组结构listdepth
1条回答
网友
1楼 · 发布于 2024-03-28 08:21:13
>>> from itertools import product
>>> i = xrange(1,3)
>>> j = xrange(3,5)
>>> k = xrange(5,7)
>>> indices = [ i, j, k ]
>>> for item in product(*indices):
        print item


(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)

相关问题 更多 >