gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:53 24 4
gpt4 key购买 nike

我正在尝试比较 2 组数据

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

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

最佳答案

使用intersection :

set2.intersection(set1)

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

根据您的评论,可能是一个字典,其中值是 bool 值,基于 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}

或者获取两个集合,用于公共(public)元素和不同元素:

st2 = set(set2)

inter = st2.intersection(set1)

diff = st2.difference(set1)

关于python - 比较两组之间的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com