python 中 set.intersection 的对面?
Opposite of set.intersection in python?
在 Python 中,您可以使用 a.intersection(b)
查找两组共有的项目。
有没有办法做到 disjoint 相反的版本? a
和 b
不通用的项目; a
中的唯一项与 b
?
中的唯一项合并
您正在寻找对称差异;仅出现在集合 a 或集合 b 中但不是同时出现的所有元素:
a.symmetric_difference(b)
来自set.symmetric_difference()
method documentation:
Return a new set with elements in either the set or other but not both.
如果 a
和 b
都是集合,您也可以使用 ^
运算符:
a ^ b
而 set.symmetric_difference()
接受任何可迭代的 other 参数。
输出相当于 (a | b) - (a & b)
,两个集合的并集减去两个集合的交集。
为 (set(a) - intersection(b)) 尝试此代码
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
输出是[1,4,5,6]
我希望,它会起作用
a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}
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]
这会循环列出 returns 不相交的列表
最好的方法是列表理解。
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]
您可以加入两个列表
在 Python 中,您可以使用 a.intersection(b)
查找两组共有的项目。
有没有办法做到 disjoint 相反的版本? a
和 b
不通用的项目; a
中的唯一项与 b
?
您正在寻找对称差异;仅出现在集合 a 或集合 b 中但不是同时出现的所有元素:
a.symmetric_difference(b)
来自set.symmetric_difference()
method documentation:
Return a new set with elements in either the set or other but not both.
如果 a
和 b
都是集合,您也可以使用 ^
运算符:
a ^ b
而 set.symmetric_difference()
接受任何可迭代的 other 参数。
输出相当于 (a | b) - (a & b)
,两个集合的并集减去两个集合的交集。
为 (set(a) - intersection(b)) 尝试此代码
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
输出是[1,4,5,6]
我希望,它会起作用
a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}
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]
这会循环列出 returns 不相交的列表
最好的方法是列表理解。
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]
您可以加入两个列表