迭代未知维度的numpy矩阵

时间:2012-07-28 00:44:09

标签: python matrix numpy enumerate

我有一个多维的numpy数组,我想迭代一遍。我希望不仅能够访问值,还能访问它们的索引。不幸的是,

for idx,val in enumerate(my_array):
当my_array是多维的时,

似乎不起作用。 (我希望idx成为一个元组)。嵌套for循环可能有效,但我不知道数组的维数,直到运行时,我知道它不适合python。我可以想到很多方法(递归,自由使用%运算符),但这些都不是'python-esque'。有一个简单的方法吗?

1 个答案:

答案 0 :(得分:7)

我想你想要ndenumerate

>>> import numpy
>>> a = numpy.arange(6).reshape(1,2,3)
>>> a
array([[[0, 1, 2],
        [3, 4, 5]]])
>>> list(numpy.ndenumerate(a))
[((0, 0, 0), 0), ((0, 0, 1), 1), ((0, 0, 2), 2), ((0, 1, 0), 3), ((0, 1, 1), 4), ((0, 1, 2), 5)]
相关问题