【问题标题】:Compare two list, and create other two lists with intersection and difference比较两个列表,并创建其他两个具有交集和差异的列表
【发布时间】:2018-10-09 08:16:20
【问题描述】:

我有 2 个列表 A 和 B。

在 B 列表中,我可以有来自列表 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 的列表(唯一)
  3. 也很高兴得到:B 中的数字,在 A 中没有共同受访者

我的做法是两个循环:

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

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

而且我不能使用else on i!=j,因为在 B 中有重复且没有顺序。

【问题讨论】:

  • 只要使用 Python 内置的set 类型即可。
  • 请在您的问题中包含所需的输出,因为我真的不确定我是否正确理解(1)和(2)。

标签: python python-3.x list


【解决方案1】:
#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)))

【讨论】:

    【解决方案2】:

    将列表转换为set,然后进行集合操作

    >>> set_A = set(A)
    >>> set_B = set(B)
    >>> list(set_A & set_B)
    [1, 3, 5, 7, 9, 14]         # set intersection
    
    >>> list(set_A - set_B)     # set difference
    [12]
    
    >>> list(set_B - set_A)
    [2]
    

    【讨论】:

      【解决方案3】:

      使用 python 你可以简单地使用 set 类型:

      list(set(A) & set(B))
      

      将返回一个列表,其中包含列表AB 之间的元素交集。

      list(set(A) - set(B))
      

      将返回一个列表,其中包含 A 中而不是 B 中的所有元素。

      反之亦然:

      list(set(B) - set(A))
      

      将返回一个列表,其中包含 B 中而不是 A 中的所有元素。

      【讨论】:

        【解决方案4】:

        您可以使用“a in L”功能,如果元素在列表中,它将返回 True。例如

        A = [1,3,5,7, 9, 12, 14]
        B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]
        
        common = []
        uncommon = []
        
        for a in A:
            if a in B:
              common.append(a)
            else:
              uncommon.append(a)
        print(common)
        print(uncommon)
        

        这应该给你一个很好的提示,告诉你如何处理另一个问题。 最好的

        【讨论】:

          【解决方案5】:

          使用set operations:

          A = [1, 3, 5, 7, 9, 12, 14]
          B = [1, 2, 3, 3, 7, 9, 7, 3, 14, 14, 1, 3, 2, 5, 5]
          
          sa = set(A)
          sb = set(B)
          
          # intersection
          l1 = list(sa & sb)
          # [1, 2, 3, 5, 7, 9, 12, 14]
          
          # differences
          l2 = list(sa - sb)
          # [12]
          l3 = list(sb - sa)
          # [2]
          

          【讨论】:

          • l1 = list(sa | sb) 和 l1 = list(sa & sb) 不是交集吗?
          • 哦,是的,这绝对比我的方法更容易。起首!
          • @AlexanderPane 我根据您的评论编辑了答案。这就是我所说的“当然”
          • @schwobaseggl 是的,我很困惑,虽然我看错了。
          猜你喜欢
          • 2013-04-25
          • 1970-01-01
          • 2014-02-26
          • 1970-01-01
          • 1970-01-01
          • 2013-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多