我试图比较两组数据
set1 = [a,b,c,d,e,f]
set2 = [a,c,e]
我如何找出set2
中set1
中的哪个变量,然后将其输出到另一个显示结果的集合?
答案 0 :(得分:8)
使用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)