假設我有這個矩陣:(不必平方)
a b c
d e f
g h i
我想回傳所有成對鄰居的串列或生成器。意義:
[[a,b], [b,c], [d,e], [e,f], [g,h], [h,i], [a,d], [b,e], [c,f], [d,g], [e,h], [f,i]]
AND(!) 添加一個選項以僅回傳以下各項的總和:a*b b*c d*e e*f g*h ... f*i
如果從示例中沒有足夠清楚地解釋這一點,那么如果兩個元素彼此相鄰,從左到右或從下向上(不是對角線!),則它們是成對的鄰居。
這是我到目前為止所做的:
def neighbors(X, returnSet=False):
'''
:param X: The matrix
:param returnSet: False[DEFAULT] = Return sum of Xi*Xj (when Xi and Xj are pairwise-neighbors)
True = Return the set of all neighbors.
:return: Depends on returnSet
'''
sum, neighbors = 0, []
for i in range(0, X.shape[0]):
for j in range(0, X.shape[1]):
if j 1 < X.shape[1]:
neighbors.append([X[i][j], X[i][j 1]]) if returnSet else None
sum = X[i][j] * X[i][j 1]
if i 1 < X.shape[0]:
neighbors.append([X[i][j], X[i 1][j]]) if returnSet else None
sum = X[i][j] * X[i 1][j]
return neighbors if returnSet else sum
這段代碼有效,但我不太喜歡它的外觀。你能想出一些比這更“酷”的演算法嗎?或者也許更有效率?我喜歡 Python 代碼簡短而簡單。
uj5u.com熱心網友回復:
與您的上一個問題基本相同,只是在兩個軸上使用雙點積(不那么漂亮)。
a = np.arange(9).reshape(3,3)
np.einsum('ij, ij->', a[1:], a[:-1]) np.einsum('ij, ij->', a[:, 1:], a[:, :-1])
Out[]: 232
neighbors(a)
Out[]: 232
如果你只想要這些對:
h = np.stack([a[:, 1:], a[:, :-1]]).transpose(1,2,0).reshape(-1, 2)
v = np.stack([a[1:], a[:-1]]).transpose(1,2,0).reshape(-1, 2)
np.vstack([h, v])
Out[]:
array([[1, 0],
[2, 1],
[4, 3],
[5, 4],
[7, 6],
[8, 7],
[3, 0],
[4, 1],
[5, 2],
[6, 3],
[7, 4],
[8, 5]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/468193.html
上一篇:數值查找非均勻二維資料的一階導數
