仅从两个列表中获取唯一元素 [英] Get only unique elements from two lists
本文介绍了仅从两个列表中获取唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个列表(可能具有不同的len):
If I have two lists (may be with different len):
x = [1,2,3,4]
f = [1,11,22,33,44,3,4]
result = [11,22,33,44]
我正在做
for element in f:
if element in x:
f.remove(element)
我要
result = [11,22,33,44,4]
推荐答案
更新:
感谢@ Ahito :
In : list(set(x).symmetric_difference(set(f)))
Out: [33, 2, 22, 11, 44]
本文有一个简洁的图表,该图表解释了对称差别.
This article has a neat diagram that explains what the symmetric difference does.
使用以下 Python的文档设置:
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
我想出了这段代码来从两个列表中获取唯一元素:
I came up with this piece of code to obtain unique elements from two lists:
(set(x) | set(f)) - (set(x) & set(f))
或稍作修改以返回 list
:
list((set(x) | set(f)) - (set(x) & set(f))) #if you need a list
这里:
-
|
运算符以x
,f
或 both 返回元素 -
&
运算符以两者x
和f
的形式返回元素 -
-
运算符从|
中减去&
的结果,并为我们提供仅在列表之一中唯一显示的元素
|
operator returns elements inx
,f
or both&
operator returns elements in bothx
andf
-
operator subtracts the results of&
from|
and provides us with the elements that are uniquely presented only in one of the lists
这篇关于仅从两个列表中获取唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文