与 python 中的 set.intersection 相反?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29947844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:11:41  来源:igfitidea点击:

Opposite of set.intersection in python?

pythonset

提问by user4847061

In Python you can use a.intersection(b)to find the items common to both sets.

在 Python 中,您可以使用a.intersection(b)查找两个集合共有的项目。

Is there a way to do the disjointopposite version of this? Items that are not common to both aand b; the unique items in aunioned with the unique items in b?

有没有办法做这个不相交的相反版本?a和不共同的项目b;中的独特物品ab?

采纳答案by Martijn Pieters

You are looking for the symmetric difference; all elements that appear only in set a or in set b, but not both:

您正在寻找对称差异;只出现在集合 a 或集合 b 中的所有元素,但不能同时出现:

a.symmetric_difference(b)

From the set.symmetric_difference()method documentation:

set.symmetric_difference()方法文档

Return a new set with elements in either the set or otherbut not both.

返回一个新集合,其中包含集合中的元素或其他元素,但不能同时包含两者。

You can use the ^operator too, if both aand bare sets:

^如果ab都设置,您也可以使用运算符:

a ^ b

while set.symmetric_difference()takes any iterable for the otherargument.

whileset.symmetric_difference()另一个参数接受任何迭代。

The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets.

输出等价于(a | b) - (a & b),两个集合的并集减去两个集合的交集。

回答by Muhammad Ammar Fauzan

Try this code for (set(a) - intersection(a&b))

试试这个代码 (set(a) -intersection(a&b))

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6]I hope, it will work

输出是[1,4,5,6]我希望的,它会起作用

回答by Kaung Yar Zar

a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}

回答by chandra singh

e, f are two list you want to check disjoint

e, f 是要检查的两个列表不相交

a = [1,2,3,4]
b = [8,7,9,2,1]

c = []
def loop_to_check(e,f):
    for i in range(len(e)):
        if e[i] not in f:
            c.append(e[i])


loop_to_check(a,b)
loop_to_check(b,a)
print(c)

## output is [3,4,8,7,9]

This loops around to list and returns the disjoint list

这会循环列出并返回不相交的列表

回答by Apeasant

The best way is a list comprehension.

最好的方法是列表理解。

a = [ 1,2,3,4]
b = [ 8,7,9,2,1]
c = [ element for element in a if element not in b] 
d = [ element for element in b if element not in a] 
print(c) 
# output is [ 3,4]
print(d) 
# output is  [8,7,9]

You can join both lists

您可以加入两个列表