比较两组之间的每个元素?

Comparing each element between 2 sets?

我正在尝试比较 2 组数据

set1 = [a,b,c,d,e,f] set2 = [a,c,e]

我如何找出 set2 中的哪个变量在 set1 中,然后将其输出到另一组显示结果?

使用intersection:

set2.intersection(set1)

或者 set(set2).intersection(set1) 如果您确实有一个列表。

根据您的评论,可能是一个字典,其中的值是布尔值,基于 set1 中的每个元素是否在交集中:

set1 = ["a","b","c","d","e","f"]
set2 = ["a","c","e"]

inter = set(set2).intersection(set1)

vals = {k:k in inter for k in set1}

print(vals)
{'a': True, 'c': True, 'b': False, 'e': True, 'd': False, 'f': False}

如果您只需要一个映射,那么也许从 set2 创建一个集合就足够了:

set1 = ["a","b","c","d","e","f"]
set2 = ["a","c","e"]

st2 = set(set2)

vals = {k: k in st2 for k in set1}

或者得到两个集合,对于共同的和不同的元素:

st2 = set(set2)

inter = st2.intersection(set1)

diff = st2.difference(set1)