交互式爱情
对于短数组,使用集合可能是最清晰,最易读的方法。另一种方法是使用numpy.intersect1d。你必须欺骗它将行视为单个值,但是......这使得事情的可读性降低了......import numpy as npA = np.array([[1,4],[2,5],[3,6]])B = np.array([[1,4],[3,6],[7,8]])nrows, ncols = A.shapedtype={'names':['f{}'.format(i) for i in range(ncols)], 'formats':ncols * [A.dtype]}C = np.intersect1d(A.view(dtype), B.view(dtype))# This last bit is optional if you're okay with "C" being a structured array...C = C.view(A.dtype).reshape(-1, ncols)对于大型数组,这应该比使用集合快得多。
Helenr
你可以使用Python的集合:>>> import numpy as np>>> A = np.array([[1,4],[2,5],[3,6]])>>> B = np.array([[1,4],[3,6],[7,8]])>>> aset = set([tuple(x) for x in A])>>> bset = set([tuple(x) for x in B])>>> np.array([x for x in aset & bset])array([[1, 4], [3, 6]])正如Rob Cowie指出的那样,这可以更简洁地完成np.array([x for x in set(tuple(x) for x in A) & set(tuple(x) for x in B)])可能有一种方法可以做到这一点,而不是从数组到元组的所有来回,但它现在不会来找我。