我试图弄清楚如何删除两组中的常用值。
set1={":dog","cat","mouse"}
set2={"bird","dog","house","fish"}
所以结果只是{"cat","mouse","bird","house","fish"}
。
我正在查看堆栈溢出并找到了这个 Removing the common elements between two lists 但是我不确定它是否特定于数字或类似旧的python格式,因为它不起作用。
在我的代码中,我首先通过执行
删除了set1line = re.sub('[:]', '', str(set1))
然后我做了:
res=list(set(line)^set(set2))
我也试过
res=list(line^set2)
但输出很奇怪
[',', 'u', 'c', '{', "'", 'o', 's', 'g', 'house', 'd', 't', 'bird', 'fish', 'm', 'dog', 'a', 'e', ' ', '}']
答案 0 :(得分:2)
有几种方法:
set1 = {":dog", "cat", "mouse"}
set2 = {"bird", "dog", "house", "fish"}
set1 = {k.replace(':', '') for k in set1}
# 3 equivalent methods
set1 ^ set2
set1.symmetric_difference(set2)
(set1 | set2) - (set1 & set2)
# {'bird', 'cat', 'fish', 'house', 'mouse'}