我一直在试图找出一种干净的python方法,用空numpy数组的每个元素填充该元素的索引值,而不使用for循环。对于一维,这很简单,您可以使用类似np.arange或基本range的东西。但是在二维和更高的维度上,我很难做到这一点。(编辑:或者像这样建立一个常规列表,然后np.array(lst)它。我想我刚刚回答了我的问题-使用列表理解?)例子:rows = 4cols = 4arr = np.empty((rows, cols, 2)) # 4x4 matrix with [x,y] locationfor y in range(rows): for x in range(cols): arr[y, x] = [y, x]'''Expected output:[[[0,0], [0,1], [0,2], [0,3]], [[1,0], [1,1], [1,2], [1,3]], [[2,0], [2,1], [2,2], [2,3]], [[3,0], [3,1], [3,2], [3,3]]]''' 最佳答案 显示的是4x4矩阵的meshgrid;您可以使用np.mgrid,然后转置结果:np.moveaxis(np.mgrid[:rows,:cols], 0, -1)#array([[[0, 0],# [0, 1],# [0, 2],# [0, 3]],# [[1, 0],# [1, 1],# [1, 2],# [1, 3]],# [[2, 0],# [2, 1],# [2, 2],# [2, 3]],# [[3, 0],# [3, 1],# [3, 2],# [3, 3]]])或使用矩阵索引 >np.dstack(np.meshgrid(np.arange(rows), np.arange(cols), indexing='ij'))#array([[[0, 0],# [0, 1],# [0, 2],# [0, 3]],# [[1, 0],# [1, 1],# [1, 2],# [1, 3]],# [[2, 0],# [2, 1],# [2, 2],# [2, 3]],# [[3, 0],# [3, 1],# [3, 2],# [3, 3]]])关于python - 用索引位置填充二维numpy数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46459684/