[英]Python find list of surrounding neighbours of a node in 2D array
I've been working on a code (Py 2.7) that generates an array of elements with each node assigned some random numbers. 我一直在研究代码(Py 2.7),该代码生成元素数组,并为每个节点分配一些随机数。 Now, I wish to make a list of the surrounding elements, and find the index of the max value.
现在,我希望列出周围的元素,并找到最大值的索引。 The array size is variable (I considered col = array column size).
数组大小是可变的(我认为col =数组列大小)。 I have assigned numbers to each node (I called it 's' in the below) so that I can find the 2D index of the array element.
我已经为每个节点分配了编号(在下面我称其为's'),以便可以找到数组元素的2D索引。 Here is what I wrote
这是我写的
rn = s/col; cn = s%col;
b = [rr[rn,cn+1],rr[rn-1,cn+1],rr[rn-1,cn],rr[rn-1,cn-1],rr[rn,cn-1],rr[rn+1,cn-1],rr[rn+1,cn],rr[rn+1,cn+1]]
ma = max(b)
a = [i for i,j in enumerate(b) if j == ma]
Is there any short method to find the neighbours without the need to number each array element ? 是否有任何简便的方法可以找到邻居而无需为每个数组元素编号? (like I did using s).
(就像我使用s一样)。
You can use numpy
for this. 您可以为此使用
numpy
。 First, let's create a random 5x5 matrix M
for testing... 首先,让我们创建一个随机的5x5矩阵
M
进行测试...
>>> M = np.random.random((5, 5))
>>> M
array([[ 0.79463434, 0.60469124, 0.85488643, 0.69161242, 0.25254776],
[ 0.07024954, 0.84918038, 0.01713536, 0.42620873, 0.97347887],
[ 0.3374191 , 0.99535699, 0.79378892, 0.0504229 , 0.05136649],
[ 0.73609556, 0.94250215, 0.67322277, 0.49043047, 0.60657825],
[ 0.71153444, 0.43242926, 0.29726895, 0.2173065 , 0.38457722]])
Now we take a slice from this matrix, N
, holding the neighbors of some central element (x, y)
现在我们从这个矩阵
N
获取一个切片,其中包含某个中心元素(x, y)
的邻居
>>> x, y = 2, 2
>>> N = M[x-1:x+2, y-1:y+2]
>>> N
array([[ 0.84918038, 0.01713536, 0.42620873],
[ 0.99535699, 0.79378892, 0.0504229 ],
[ 0.94250215, 0.67322277, 0.49043047]])
We can now get a new matrix showing which of the elements of the orginal matrix M
is equal to the max
from N
现在我们可以得到一个新矩阵,该矩阵显示原始矩阵
M
哪些元素等于N
的max
>>> M == N.max()
array([[False, False, False, False, False],
[False, False, False, False, False],
[False, True, False, False, False],
[False, False, False, False, False],
[False, False, False, False, False]], dtype=bool)
Now we can use numpy.where
to get the index of the element(s) that are True
in this matrix. 现在,我们可以使用
numpy.where
来获取此矩阵中True
元素的索引。 zip
those to get a list of tuples. zip
以获取元组列表。
>>> zip(*np.where(M == N.max()))
[(2, 1)]
Note that those are the positions in the original matrix M
, ie they could contain tuples that are not in N
. 注意,这些是原始矩阵
M
中的位置,即它们可能包含不在N
元组。 Alternatively, you can get just the maximum values in N
, but then you'll have to add x-1
and y-1
as offset afterwards. 或者,您可以只获得
N
的最大值,但是之后必须将x-1
和y-1
作为偏移量相加。
>>> zip(*np.where(N == N.max()))
[(1, 0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.