简体   繁体   English

查找不在两个列表的交集中的元素

[英]Find elements NOT in the intersection of two lists

So I know how to find the intersection of two lists by doing: 所以我知道如何找到两个列表的交集:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

But what is the best way to find all the elements that are not included in the intersection. 但是找到交叉点中未包含的所有元素的最佳方法是什么。 My initial idea is to create a union of the two lists and then remove all the elements from the intersection from the union, as such: 我最初的想法是创建两个列表的联合,然后从联合中删除交集中的所有元素,如下所示:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> intersection = list(set(a) & set(b))
>>> union = list(set(a) | set(b))
>>> non_intersection = intersection - union
[2, 4, 6]

Is this the best way to do this or is there another way? 这是最好的方法吗?还是有另一种方式?

I usually prefer a shortcut: 我通常更喜欢捷径:

set(a) ^ set(b)
{2, 4, 6}

Symmetric difference? 对称差异?

>>> set(a).symmetric_difference(b)
{2, 4, 6}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM