迭代未知维的numpy矩阵 [英] Iterate over numpy matrix of unknown dimension

查看:138
本文介绍了迭代未知维的numpy矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要迭代的多维numpy数组.我希望不仅可以访问值,还可以访问它们的索引.不幸的是,

I have a multidimensional numpy array I'd like to iterate over. I want to be able to access not only the values, but also their indices. Unfortunately,

for idx,val in enumerate(my_array):

当my_array为多维时,

似乎不起作用. (我希望idx成为一个元组).嵌套的for循环可能有用,但是直到运行时我才知道数组的维数,而且我知道它无论如何都不适合python.我可以想到许多方法来执行此操作(递归,%运算符的自由使用),但这些方法似乎都不是"python风格的".有没有简单的方法?

doesn't seem to work when my_array is multidimensional. (I'd like idx to be a tuple). Nested for loops might work, but I don't know the number of dimensions of the array until runtime, and I know it's not appropriate for python anyway. I can think of a number of ways to do this (recursion, liberal use of the % operator), but none of these seem very 'python-esque'. Is there a simple way?

推荐答案

我认为您想要 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)]

这篇关于迭代未知维的numpy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆