我试图弄清楚如何在两组中删除公用值。

set1={":dog","cat","mouse"}
set2={"bird","dog","house","fish"}


因此结果只是{"cat","mouse","bird","house","fish"}

我在堆栈溢出上寻找,发现了这个
Removing the common elements between two lists
但是我不确定它是特定于数字还是像旧的python格式,因为它不起作用。

在我的代码中,我首先通过以下方法摆脱了set1中的:

line = 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', ' ', '}']

最佳答案

有几种方法:

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'}

关于python - 在两组python3中删除常见的字符串元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48818286/

10-15 09:18