python - 对多维索引(任意维度)的列表表示的高效迭代

标签 python algorithm recursion multidimensional-array tree

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

indices = [ i, j, k ]

在哪里

i = xrange(1,3)
j = xrange(3,5)
k = xrange(5,7)

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

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)

这工作正常,但我想知道,是否有更有效的 Pythonic 方式来做到这一点?我尝试查看 itertools 模块,但没有发现任何问题。

最佳答案

>>> 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)

关于python - 对多维索引(任意维度)的列表表示的高效迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195260/

相关文章:

python - 如何正确解码 RTF 中的十六进制值

python - 如果字符串与列表中的字符串匹配,如何从句子中删除字符串

python - 如何在 python 中正确编码可能是中文的编码?

java - BigInteger 使用什么算法将整数转换为字节数组

javascript - 如何使用 JavaScript/Prototype 1.7 递归搜索对象树并根据键/值返回匹配对象

java - 这个设计有什么问题导致无限循环?

javascript - 迭代树序列化函数

python - 使用 Pool 和 multiprocessing 同时将两个函数应用于两个列表

algorithm - 遍历不同大小的多个列表的最佳方法是什么?

algorithm - 什么散列函数在对 n 个键进行散列时产生最大碰撞次数?