Python通过numpy中的二维数组进行枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21004538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:46:22  来源:igfitidea点击:

Python enumerate through 2D array in numpy

pythonarraysnumpyenumerate

提问by rlms

I want a function that behaves like enumerate, but on numpy arrays.

我想要一个行为类似于enumerate, 但在 numpy 数组上的函数。

>>> list(enumerate("hello"))
[(0, "h"), (1, "e"), (2, "l"), (3, "l"), (4, "o")]

>>> for x, y, element in enumerate2(numpy.array([[i for i in "egg"] for j in range(3)])):
        print(x, y, element)

0 0 e
1 0 g
2 0 g
0 1 e
1 1 g
2 1 g
0 2 e
1 2 g
2 2 g

Currently I am using this function:

目前我正在使用这个功能:

def enumerate2(np_array):
    for y, row in enumerate(np_array):
        for x, element in enumerate(row):
            yield (x, y, element)

Is there any better way to do this? E.g. an inbuilt function (I couldn't find any), or a different definition that is faster in some way.

有没有更好的方法来做到这一点?例如,一个内置函数(我找不到任何函数),或者在某些方面更快的不同定义。

采纳答案by Jaime

You want np.ndenumerate:

你想要np.ndenumerate

>>> for (x, y), element in np.ndenumerate(np.array([[i for i in "egg"] for j in range(3)])):
...     print(x, y, element)
... 
(0L, 0L, 'e')
(0L, 1L, 'g')
(0L, 2L, 'g')
(1L, 0L, 'e')
(1L, 1L, 'g')
(1L, 2L, 'g')
(2L, 0L, 'e')
(2L, 1L, 'g')
(2L, 2L, 'g')