【问题标题】:Remove elements from list that is in another list while keeping duplicates [duplicate]从另一个列表中的列表中删除元素,同时保留重复项[重复]
【发布时间】:2021-03-20 14:24:24
【问题描述】:

我想删除 l1 中 l2 中的元素,同时保留重复项。

输入:

l1 = [a, b, b, a, c, c, a]
l2 = [c, b]

输出:

l3 = [a, b, a, c, a]

我试图为此找到一个好的答案,但我似乎找到的只是这样做的方法,这也删除了重复项。首先,我尝试使用 set() 执行此操作,直到我意识到它会删除重复项,然后我尝试使用 numpy 和 setdiff1d 但无法使其正常工作。使用列表理解,如

[item for item in x if item not in y]

还删除了重复项。从列表中删除其他列表中的元素而不删除重复项的最简单方法是什么?列表的顺序并不重要。

【问题讨论】:

  • 是否保证您的列表l2 不会有重复项?它 l2 的预期输出是什么,例如[c, b, b]
  • 这还不清楚。您要删除l2 的每个值的第一次出现,还是全部删除,但如果它们出现在一组 2 中,则保留一个?在这种情况下,如果连续有 3 个呢?

标签: python python-3.x list


【解决方案1】:

你需要更复杂一点的循环:


l1 = ['a', 'b', 'b', 'a', 'c', 'c', 'a']
l2 = ['c', 'b']
l3=[]
for item in l1:
    if item in l2:
        l2.remove(item)
    else:
        l3.append(item)
>>>l3
['a', 'b', 'a', 'c', 'a']

【讨论】:

  • 赞成,但list 中的removein 运算符的时间复杂度为O(n)。所以当有一些大数据时它可能会表现不佳。
【解决方案2】:

只需使用Counter:

from collections import Counter

l1 = ["a", "b", "b", "a", "c", "c", "a"]
l2 = ["c", "b"]

print(list((Counter(l1)-Counter(l2)).elements()))

结果:

['a', 'a', 'a', 'b', 'c']

【讨论】:

  • “列表的顺序并不重要。”
【解决方案3】:
def remove_dup(l1,l2):
  d={}
  l3=[]
  for i in l1:
    if i not in d:
      d[i]=1
    else:
      d[i]+=1
  for i in l2:
    if i in d:
      d[i]-=1

  for i in d:
    for count in range(d[i]):
      l3.append(i)

  return l3




l1 = ["a", "b", "b", "a", "c","c", "a"]
l2 = ["c", "b"]
print(remove_dup(l1,l2))
'''


You can use a dict to store the count for the elements in the first loop , then iterate through the second one reducing the count and then finally append it in l3 ,

【讨论】:

    【解决方案4】:

    最简单快捷的方法:

    l3 = l1.copy()
    for x in l2:
        l3.remove(x)
    
    1. 您制作了要弹出元素的列表的副本
    2. 对于第二个列表中的每个元素,您都尝试在第一个列表中删除它

    【讨论】:

    • 不要对副作用使用列表推导。
    • 好主意,不建议在没有赋值的情况下使用列表推导,尝试使用:将其更改为命令式
    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 2017-11-23
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2021-04-15
    相关资源
    最近更新 更多