<p>首先是一个示例<code>data</code>;我猜这是一个nxnx3数组,其数据类型为<code>uint8</code></p>
<pre><code>In [791]: data=np.random.randint(0,256,(8,8,3),dtype=np.uint8)
</code></pre>
<p>{t>在一个新的数组中返回一个新的<cdt>方法:</p>
^{pr2}$
<p><code>data.shape=(1,-1,3)</code>也能做到。但是为什么首字母<code>1</code>?在</p>
<p>取而代之的是:</p>
^{3}$
<p>在我的例子中,有一组64个独特的项目-这并不奇怪,因为我是如何生成这些值的</p>
<p>你什么都不做<code>data.reshape</code>行和<code>{tuple(item) for item in data[0]}</code>解释了为什么它似乎只在图片的第一行工作。在</p>
<p>我猜<code>selection_data</code>是类似的3个项目元组,例如:</p>
<pre><code>In [801]: selection_data = {tuple(data[1,3,:]), (1,2,3), tuple(data[5,5,:])}
In [802]: selection_data
Out[802]: {(1, 2, 3), (49, 132, 26), (76, 131, 16)}
In [803]: selection_data&aset
Out[803]: {(49, 132, 26), (76, 131, 16)}
</code></pre>
<p>您没有说明您试图在何处使用<code>tolist</code>,但我猜是在生成元组集时。在</p>
<p>但奇怪的是,<code>tolist</code>加速了转换:</p>
<pre><code>In [808]: timeit {tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 57.7 µs per loop
In [809]: timeit {tuple(item) for item in data.reshape(-1,3)}
1000 loops, best of 3: 239 µs per loop
In [815]: timeit data.reshape(-1,3).tolist()
100000 loops, best of 3: 19.8 µs per loop
In [817]: timeit {tuple(item.tolist()) for item in data.reshape(-1,3)}
10000 loops, best of 3: 100 µs per loop
</code></pre>
<p>因此,对于这种列表和集合操作,我们最好马上跳转到列表格式。在</p>
<p><code>numpy</code>有一些集合函数,例如<code>np.in1d</code>。这只对1d数组进行操作,但是正如在一些<code>unique row</code>问题中所演示的那样,我们可以通过将2d数组看作一个结构化数组来解决这个问题。我得摆弄才能走到这一步:</p>
<pre><code>In [880]: dt=np.dtype('uint8,uint8,uint8')
In [881]: data1=data.reshape(-1,3).view(dt).ravel()
In [882]: data1
Out[882]:
array([(41, 145, 254), (138, 144, 7), (192, 241, 203), (42, 177, 215),
(78, 132, 87), (221, 176, 87), (107, 171, 147), (231, 13, 53),
...
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
</code></pre>
<p>构造具有相同结构化数组性质的选择:</p>
<pre><code>In [883]: selection=[data[1,3,:],[1,2,3],data[5,5,:]]
In [885]: selection=np.array(selection,np.uint8).view(dt)
In [886]: selection
Out[886]:
array([[(49, 132, 26)],
[(1, 2, 3)],
[(76, 131, 16)]],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
</code></pre>
<p>因此<code>selection</code>中的项目也可以在<code>data1</code>中找到:</p>
<pre><code>In [888]: np.in1d(selection,data1)
Out[888]: array([ True, False, True], dtype=bool)
</code></pre>
<p>在<code>data1</code>中选择的项目包括:</p>
<pre><code>In [890]: np.where(np.in1d(data1,selection))
Out[890]: (array([11, 45], dtype=int32),)
</code></pre>
<p>或是在未展开的形状</p>
<pre><code>In [891]: np.where(np.in1d(data1,selection).reshape(8,8))
Out[891]: (array([1, 5], dtype=int32), array([3, 5], dtype=int32))
</code></pre>
<p>我用来生成<code>selection</code>的相同的(1,3)和(5,5)项。在</p>
<p><code>in1d</code>时间安排很有竞争力:</p>
<pre><code>In [892]: %%timeit
...: data1=data.reshape(-1,3).view(dt).ravel()
...: np.in1d(data1,selection)
...:
10000 loops, best of 3: 65.7 µs per loop
In [894]: timeit selection_data&{tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 91.5 µs per loop
</code></pre>