python - 遍历一个numpy数组

有没有更简洁的替代方法:

for x in xrange(array.shape[0]):
    for y in xrange(array.shape[1]):
        do_stuff(x, y)

我想出了这个:

for x, y in itertools.product(map(xrange, array.shape)):
    do_stuff(x, y)

这节省了一个缩进,但仍然很丑。

我希望看起来像这样的伪代码:

for x, y in array.indices:
    do_stuff(x, y)

有类似的东西吗?

最佳答案

我认为您正在寻找 ndenumerate .

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

关于性能。它比列表理解要慢一些。

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

如果您担心性能,您可以通过查看 ndenumerate 的实现来进一步优化,它做了两件事,转换为数组和循环。如果你知道你有一个数组,你可以调用平面迭代器的 .coords 属性。

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

https://stackoverflow.com/questions/6967463/

相关文章:

linux - 监听网络端口并将数据保存到文本文件

python - 使用 POST 从 Python 脚本发送文件

linux - 是否有将随机垃圾字节写入文件的命令?

python - 如何在 Anaconda (Conda) 环境中跟踪 pip 安装的软件包?

python - 检测人脸然后自动裁剪图片

python - 排除 os.walk 中的目录

linux - 如何给 Linux 用户 sudo 访问权限?

linux - 未生成核心转储文件

c - 如何捕获 Control+D 信号?

python - 为什么 PyCharm 建议将方法更改为静态?