<pre><code>import numpy as np
a = np.array([0,1,2,3,4,5,6,7,8,9])
num_neighbor=3
for index in range(len(a)):
left = a[:index][-num_neighbor:]
right= a[index+1:num_neighbor+index+1]
print(index,left,right)
</code></pre>
<p>收益率</p>
<pre><code>(0, array([], dtype=int32), array([1, 2, 3]))
(1, array([0]), array([2, 3, 4]))
(2, array([0, 1]), array([3, 4, 5]))
(3, array([0, 1, 2]), array([4, 5, 6]))
(4, array([1, 2, 3]), array([5, 6, 7]))
(5, array([2, 3, 4]), array([6, 7, 8]))
(6, array([3, 4, 5]), array([7, 8, 9]))
(7, array([4, 5, 6]), array([8, 9]))
(8, array([5, 6, 7]), array([9]))
(9, array([6, 7, 8]), array([], dtype=int32))
</code></pre>
<hr/>
<p>当<code>index<num_neighbor</code>时<code>a[index-num_neighbor:index]</code>不起作用的原因是<a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">slicing rules #3 and #4</a>:</p>
<p>给定<code>s[i:j]</code>:</p>
<blockquote>
<p>If i or j is negative, the index is relative to the end of the string:
len(s) + i or len(s) + j is substituted.</p>
<p>The slice of s from i to j is defined as the sequence of items with
index k such that i <= k < j. If i or j is greater than len(s), use
len(s). If i is omitted or None, use 0. If j is omitted or None, use
len(s). If i is greater than or equal to j, the slice is empty.</p>
</blockquote>
<p>所以当<code>index=1</code>,然后<code>a[index-num_neighbor:index] = a[-2:1] = a[10-2:1] = a[8:1] = []</code>。</p>