【问题标题】:Find common items between two lists with repeated elements python 3查找两个具有重复元素的列表之间的共同项目python 3
【发布时间】:2019-09-09 03:21:22
【问题描述】:

很多posts 或How to find list intersection? 旨在找到两个列表之间的unique 项目:

这是我的两个列表:

list1=[1, 2, 2, 3, 3, 4, 4, 5, 10, 12] 
list2=[1, 1, 2, 2, 3, 4, 4, 5, 8, 18]

我的答案是找到共同的物品,可以重复的物品。例如,一个1 出现在这两个列表中,因此,res 应该包含一个1。两个列表中出现了两个2,res应该包含两个2,以此类推

res = [1 ,2, 2, 3, 4, 4, 5]

顺序无所谓,我的尝试是使用:

res = [x for x in list2 if x in list1]
# res = [1, 1, 2, 2, 3, 4, 4, 5] by above code

但是,它不正确,该怎么做?

【问题讨论】:

  • 其实我的结果列表可以包含重复项。
  • 该页面上有适合您问题的答案。
  • @DYZ 没有...该问题的所有答案都删除了重复的交叉点,因此在 jason 的问题中强调 unique。

标签: python-3.x list repeat


【解决方案1】:

我能想到的唯一方法是从 list2 中删除项目:

list1 = [1, 2, 2, 3, 3, 4, 4, 5, 10, 12]
list2 = [1, 1, 2, 2, 3, 4, 4, 5, 8, 18]

res = []

for x in list1:
    if x in list2:
        res.append(x)
        list2.remove(x)

print(res)

我很好奇是否有更好的答案。

【讨论】:

    【解决方案2】:

    传统方法行不通,因为在第二个 for 循环中,它再次迭代整个列表并再次找到相同的元素,即使它之前考虑过。

    您需要一种机制来消除已经考虑的元素。
    例如:当您在list2 上迭代list1 并遇到3。 在第一次迭代中,您将在 list2 中找到它。但是,当您继续考虑下一个元素,即 3 时,您会再次发现它是 list2 中的一个公共元素,因为您从一开始就迭代了 list2。

    这里有一个解决方案:

    一旦我们在list2 中遇到重复元素,我们会将其从list2 中删除。

    
    a = [1, 2, 2, 3, 3, 4, 4, 5, 10, 12]
    b = [1, 1, 2, 2, 3, 4, 4, 5, 8, 18]
    
    def remove_duplicates(x,y):
        res = []
        for i in x:
            for j in y:
                if j == i:
                    res.append(j)
                    y.remove(j)
        return res
        
    print(remove_duplicates(a,b))
    

    使用函数式编程的另一种方法是将list2 转换为使用map() 的数据结构,以便它为列表中的每个元素保存两个值:[(1, True),(2, True), ...]

    迭代时,只访问设置为True的元素
    而且,每当我们找到一个共同的元素时,我们都会将该元素的 True 设置为 False

    【讨论】:

      【解决方案3】:

      基于 Counter 的替代解决方案:

      import collections
      
      def intersection(A,B):
          c_a=collections.Counter(A)
          c_b=collections.Counter(B)
          duplicates=[]
          for c in c_a:
              duplicates+=[c]*min(c_a[c],c_b[c])
          return duplicates
      
      
      list1=[1, 2, 2, 3, 3, 4, 4, 5, 10, 12] 
      list2=[1, 1, 2, 2, 3, 4, 4, 5, 8, 18]
      print(intersection(list1,list2))
      

      【讨论】:

        猜你喜欢
        • 2021-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        相关资源
        最近更新 更多