<pre><code>import numpy as np
def asvoid(arr):
"""
View the array as dtype np.void (bytes)
This views the last axis of ND-arrays as bytes so you can perform comparisons on
the entire row.
http://stackoverflow.com/a/16840350/190597 (Jaime, 2013-05)
Warning: When using asvoid for comparison, note that float zeros may compare UNEQUALLY
>>> asvoid([-0.]) == asvoid([0.])
array([False], dtype=bool)
"""
arr = np.ascontiguousarray(arr)
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))
def in1d_index(a, b):
voida, voidb = map(asvoid, (a, b))
return np.where(np.in1d(voidb, voida))[0]
a = np.array([[4, 6],[2, 6],[5, 2]])
b = np.array([[1, 7],[1, 8],[2, 6],[2, 1],[2, 4],[4, 6],[4, 7],[5, 9],[5, 2],[5, 1]])
print(in1d_index(a, b))
</code></pre>
<p>印刷品</p>
^{pr2}$
<p>这相当于Matlab的[3,6,9],因为Python使用基于0的索引。在</p>
<p>一些注意事项:</p>
<ol>
<li>索引按递增顺序返回。它们不一致
到<code>b</code>中<code>a</code>项的位置。在</li>
<li>asvoid适用于整数数据类型,但使用asvoid时要小心
对于浮点数据类型,因为<code>asvoid([-0.]) == asvoid([0.])</code>返回
<code>array([False])</code>。在</li>
<li>asvoid最适合于连续数组。如果数组不是连续的,数据将被复制到一个连续的数组中,这将降低性能。在</li>
</ol>
<hr/>
<p>尽管有这些注意事项,但为了速度起见,还是可以选择使用<code>in1d_index</code>:</p>
^{3}$
<p>因此<code>in1d_index</code>比<code>in1d_index</code>快了大约65倍(对于长度为低千分之一的数组),但是再次注意,这种比较并不完全是苹果对苹果,因为<code>in1d_index</code>以递增顺序返回索引,而{<cd8>}返回{<cd1>}在{<cd2>中显示的顺序行中的索引。在</p>