<p>首先,让我们探讨一下简单删除的替代方法(不考虑起始位置的更改问题):</p>
<p>首先用唯一且易于识别的值创建一个<code>x</code>:</p>
<pre><code>In [787]: x = list(range(10))
In [788]: x
Out[788]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>一个列表理解方法-也许不是最快的,但相当清楚,没有bug:</p>
<pre><code>In [789]: [v for i,v in enumerate(x) if i not in x_remove]
Out[789]: [0, 2, 3, 6, 7, 8, 9]
</code></pre>
<p>你的<code>np.delete</code>方法:</p>
<pre><code>In [790]: np.delete(x, x_remove)
Out[790]: array([0, 2, 3, 6, 7, 8, 9])
</code></pre>
<p>它的缺点是将<code>x</code>转换为数组,这不是一项简单的任务(时间方面)。它还生成了一个新数组。我猜是慢了点。你知道吗</p>
<p>就地清除:</p>
<pre><code>In [791]: y=x[:]
In [792]: for i in x_remove:
...: del y[i]
...:
In [793]: y
Out[793]: [0, 2, 3, 4, 6, 8, 9]
</code></pre>
<p>哦-错了。我们需要从头开始(最大索引)。这是一个众所周知的Python“食谱”:</p>
<pre><code>In [794]: y=x[:]
In [795]: for i in x_remove[::-1]:
...: del y[i]
...:
...:
In [796]: y
Out[796]: [0, 2, 3, 6, 7, 8, 9]
</code></pre>
<p>在幕后<code>np.delete</code>采取了一种蒙蔽的方式:</p>
<pre><code>In [797]: arr = np.array(x)
In [798]: arr
Out[798]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [799]: mask = np.ones(arr.shape, bool)
In [800]: mask[x_remove] = False
In [801]: mask
Out[801]:
array([ True, False, True, True, False, False, True, True, True,
True])
In [802]: arr[mask]
Out[802]: array([0, 2, 3, 6, 7, 8, 9])
</code></pre>
<hr/>
<p>现在来讨论将<code>x_remove</code>应用于<code>x</code>片的问题。<code>x</code>的切片没有切片参数的记录。也就是说,您不能轻易确定<code>y = x[2:]</code>缺少两个值。(好吧,我可以通过比较<code>x</code>和<code>y</code>的一些属性来推断,但不能仅从<code>y</code>来推断)。你知道吗</p>
<p>因此,无论如何进行删除,都必须首先调整<code>x_remove</code>的值。你知道吗</p>
<pre><code>In [803]: x2 = np.array(x_remove)-2
In [804]: x2
Out[804]: array([-1, 2, 3])
In [805]: [v for i,v in enumerate(x[2:]) if i not in x2]
Out[805]: [2, 3, 6, 7, 8, 9]
</code></pre>
<p>这是可行的,但是<code>-1</code>可能是一个问题。我们不希望它意味着<code>the last element</code>。所以为了安全,我们必须先过滤掉阴性指标。你知道吗</p>
<pre><code>In [806]: np.delete(x[2:], x2)
/usr/local/bin/ipython3:1: FutureWarning: in the future negative indices will not be ignored by `numpy.delete`.
#!/usr/bin/python3
Out[806]: array([2, 3, 6, 7, 8, 9])
</code></pre>
<p>如果<code>delete</code>不忽略负指数,它可能会得到这样一个掩码-末尾有一个<code>False</code>:</p>
<pre><code>In [808]: mask = np.ones(arr[2:].shape, bool)
In [809]: mask[x2] = False
In [810]: mask
Out[810]: array([ True, True, False, False, True, True, True, False])
</code></pre>