比较两个列表,并创建具有交集和差的其他两个列表

编程入门 行业动态 更新时间:2024-10-16 15:58:00
本文介绍了比较两个列表,并创建具有交集和差的其他两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有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]

我要创建:

  • 创建一个列表,该列表的ID位于A中,位于B中(唯一)
  • 创建一个在A中但在B中没有对应ID(唯一)的ID列表
  • 也很高兴: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)))

    更多推荐

    比较两个列表,并创建具有交集和差的其他两个列表

    本文发布于:2023-11-29 12:29:59,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1646399.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:两个   列表

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!