我有以下代码沿着与通常返回的对角线正交的对角线进行迭代np.diagonal
。它从位置 (0, 0) 开始,朝着右下角的坐标前进。
该代码按预期工作,但它的所有循环都不是很麻木,并且在必须创建许多数组来完成这个技巧时效率低下。
所以我想知道是否有更好的方法来做到这一点,因为我看不到我将如何跨越我的数组或使用 numpy 的对角线方法以更好的方式来做到这一点(尽管我希望有一些技巧我会失败查看)。
import numpy as np
A = np.zeros((4,5))
#Construct a distance array of same size that uses (0, 0) as origo
#and evaluates distances along first and second dimensions slightly
#differently so that no values in the array is the same
D = np.zeros(A.shape)
for i in range(D.shape[0]):
for j in range(D.shape[1]):
D[i, j] = i * (1 + 1.0 / (grid_shape[0] + 1)) + j
print D
#[[ 0. 1. 2. 3. 4. ]
# [ 1.05882353 2.05882353 3.05882353 4.05882353 5.05882353]
# [ 2.11764706 3.11764706 4.11764706 5.11764706 6.11764706]
# [ 3.17647059 4.17647059 5.17647059 6.17647059 7.17647059]]
#Make a flat sorted copy
rD = D.ravel().copy()
rD.sort()
#Just to show how it works, assigning incrementing values
#iterating along the 'orthagonal' diagonals starting at (0, 0) position
for i, v in enumerate(rD):
A[D == v] = i
print A
#[[ 0 1 3 6 10]
# [ 2 4 7 11 14]
# [ 5 8 12 15 17]
# [ 9 13 16 18 19]]
编辑
澄清一下,我想逐个元素地遍历整个A
代码,但是按照上面代码调用的顺序(显示在 final 中print
)。
迭代沿对角线的哪个方向(如果 1 和 2 交换放置,以及 3 和 5 等A
)并不重要,只要对角线与 A 的主对角线正交(由 产生的对角线np.diag(A)
)。
这个问题的应用程序/原因在我之前的问题中(在该问题底部的解决方案部分中):Constructing a 2D grid from 也许不完整的候选人列表