求两个数组的非相交值

2024-05-19 15:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有两个numpy数组,并且想找到不相交的值,我该怎么做?在

这里有一个我无法理解的简短例子。在

a = ['Brian', 'Steve', 'Andrew', 'Craig']
b = ['Andrew','Steve']

我想找到不相交的值。在这种情况下,我希望我的输出是:

^{pr2}$

与我想要的相反的是:

c=np.intersect1d(a,b)

它回来了

['Andrew' 'Steve']

Tags: numpynp情况数组例子stevebrianandrew
3条回答

假设您的问题中显示的对象都不是Numpy数组,您不需要Numpy来实现这一点:

c = list(set(a).symmetric_difference(b))

如果必须使用Numpy数组作为输出,那么创建一个Numpy数组很简单:

^{pr2}$

{cd1>元素不按这个顺序出现。如果是,则需要说明预期顺序。)

另外,还有一个纯粹的裸体解决方案,但我个人觉得很难读懂:

c = np.setdiff1d(np.union1d(a, b), np.intersect1d(a, b))

您可以使用setxor1d。根据documentation

Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the input arrays.

用法如下:

import numpy

a = ['Brian', 'Steve', 'Andrew', 'Craig']
b = ['Andrew','Steve']

c = numpy.setxor1d(a, b)

执行此操作将导致c的值为array(['Brian', 'Craig'])。在

对于python数组,这应该可以做到

c=[x for x in a if x not in b]+[x for x in b if x not in a]

它首先从a中收集不在b中的所有元素,然后从b中添加不在a中的所有元素。这样可以得到a或b中的所有元素,但不能同时包含在这两个元素中。在

相关问题 更多 >