从列表中删除在另一个列表中出现的元素的次数与在其他列表中出现的次数相同

时间:2018-06-12 14:30:56

标签: python

我有list1和list2。 list2是必须从list1中删除的一组单词,例如:

list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i','i', 'me', 'me']

list2=["i","me"]

输出应为:

list3=['paste', 'text', 'text', 'here', 'here', 'here', 'my','i','i','me']

已经提出了类似的问题,但他们也删除了所有重复的问题。但是我想在list2中删除list1中的元素,就像它们在list2中出现的那样多次

2 个答案:

答案 0 :(得分:2)

长列表的内存效率低,但会保留排序:

list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i','i', 'me', 'me']
list2=["i","me"]

list3 = list1[:]                # Copy list1 -> list3
for rem_word in list2:          # Iterate over list2 as rem_word
    list3.remove(rem_word)      # Remove rem_word from list3

print(list3)

如果list2的元素保证在list1中(数量足以将它们全部删除)。

否则,

list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i','i', 'me', 'me']
list2=["i","me","zzz"]

list3 = list1[:]                # Copy list1 -> list3
for rem_word in list2:          # Iterate over list2 as rem_word
    try:
        list3.remove(rem_word)  # Remove rem_word from list3
    except ValueError: pass

print(list3)

答案 1 :(得分:1)

您可以使用enumerate

from collections import Counter
list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i','i', 'me', 'me']
list2=["i","me", "text"]
d = Counter(list2)
new_d = [c for i, c in enumerate(list1) if c not in d or sum(a == c for a in list1[:(i if i < len(list1)-1 else i+1)]) >= d[c]]

输出:

['paste', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me']