生成网格索引

Generating grid indices

我想生成一个二维数组 [x_i, y_j],其中 i = 0, 1, ..., N1, j = 0, 1, ..., N2 不执行双 for 循环。

鉴于 N1N2(以及可选的起始数字),我希望输出如下:

[[0, 0], [0, 1], [0, 2], ..., [0, N1-1]  
 [1, 0], [1, 1], [1, 2], ..., [1, N1-1]  
 .  
 .  
 .  
 [N2-1, 0], [N2-1, 1], [N2-1, 2], ..., [N2-1, N1-1]]  

而且,我想避免这样的事情:

arr_all = []
for n2 in range(N2):
  arr_row = []
  for n1 in range(N1):
    arr = [n1, n2] 
    arr_row.append(arr)
  arr_all.append(arr_row)

您可以使用 np.indices to generate the entries of the array, and then use np.dstack 将元素重新排列为所需的输出:

import numpy as np

n1 = 5
n2 = 5
print(np.dstack(np.indices((n1, n2))))

这输出:

[[[0 0]
  [0 1]
  [0 2]
  [0 3]
  [0 4]]

 [[1 0]
  [1 1]
  [1 2]
  [1 3]
  [1 4]]

 [[2 0]
  [2 1]
  [2 2]
  [2 3]
  [2 4]]

 [[3 0]
  [3 1]
  [3 2]
  [3 3]
  [3 4]]

 [[4 0]
  [4 1]
  [4 2]
  [4 3]
  [4 4]]]

在 python 中实现这一点的典型方法是列表理解。它有点仍然是一个双for循环,但它更简洁:

n1 = 4
n2 = 3   
result = [[[i, j] for j in range(n1)] for i in range(n2)]

这使得 result 的:

[[[0, 0], [0, 1], [0, 2], [0, 3]],
 [[1, 0], [1, 1], [1, 2], [1, 3]],
 [[2, 0], [2, 1], [2, 2], [2, 3]]]

如果你想要一个单一的嵌套那么它只是:

[[i, j] for i in range(n2) for j in range(n1)]

这使得:

[
  [0, 0],[0, 1],[0, 2],[0, 3],
  [1, 0],[1, 1],[1, 2],[1, 3],
  [2, 0],[2, 1],[2, 2],[2, 3]
]