回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我想得到一个np.数组. 你知道吗</p>
<p>数组看起来像:</p>
<pre><code>x = np.array([ [1, 2, 3, 4 ],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ])
</code></pre>
<p>我得到的是:</p>
<pre><code>i = 2
j = 2
n = x[i,j-1], x[i,j], x[i,j+1], x[i-1,j], x[i+1,j], x[i-1,j-1], x[i+1,j+1], x[i+1,j-1], x[i-1,j+1]
</code></pre>
<p>这是回报(我想要的)</p>
<pre><code>(10, 11, 12, 7, 15, 6, 16, 14, 8)
</code></pre>
<p>但也有一些bug,比如当我需要的neightbour值</p>
<pre><code>i = 3
j = 3
</code></pre>
<p>这就产生了:</p>
<pre><code>Exception has occurred: IndexError
index 4 is out of bounds for axis 1 with size 4
</code></pre>
<p>另一个解决方案是:</p>
<pre><code>def find_neighbors(m, i, j, dist=1):
return [row[max(0, j-dist):j+dist+1] for row in m[max(0,-1):i+dist+1]]
</code></pre>
<p>以及</p>
<pre><code>n = find_neighbors(x, i, j)
</code></pre>
<p>这使我有许多邻舍,但我设立的时候,并没有把所有的邻舍都给我</p>
<pre><code>i = 0
j = 0
</code></pre>
<p>因为它只会给我:</p>
<pre><code>[array([1, 2]), array([5, 6])]
</code></pre>
<p>有人能解决这个问题吗?你知道吗</p>
<p>谢谢你!你知道吗</p>