比较两个列表,并创建具有交集和差的其他两个列表 [英] Compare two list, and create other two lists with intersection and difference

查看:86
本文介绍了比较两个列表,并创建具有交集和差的其他两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个列表A和B.

在B列表中,我可以包含列表A中的多个元素.

In the B list I can have multiple elements from list A.

例如:

A = [1,3,5,7, 9, 12, 14]
B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]

我要创建:

  1. 创建一个列表,该列表的ID位于A中,位于B中(唯一)
  2. 创建一个在A中但在B中没有对应ID(唯一)的ID列表
  3. 也很高兴:B中没有A的数字的数字.

我的方法是两个循环:

l1 = []   
l2 = []
for i in A:
    for j in B:
      if i == j
       l1.append[i]
...
l1 = set(l1)

我不知道这是否是一个好方法,再加上2)点(b中没有什么).

I don't know if this is a good approach, plus remains the 2) point(what is not in b).

由于重复且B中没有顺序,所以我不能使用else on i!=j.

And I can't use else on i!=j, because of repetitions and no order in B.

推荐答案

#to create a list with ids that are in A and found in B (unique)
resultlist=list(set(A)&set(B))
print(list(set(A)&set(B)))


#to create a list of ids that are in A and have no corresponding in B (unique)
print(list(set(A)-set(B)))


#the numbers in B, that don't have a corespondent in A
print(list(set(B)-set(A)))

这篇关于比较两个列表,并创建具有交集和差的其他两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆