Home > Software engineering >  How to compare two lists and remove elements in python
How to compare two lists and remove elements in python

Time:09-27

I have two lists. I am trying to remove all the elements in the first list occurred prior to any element in the second list. This should be happened only once. As for an example: Let,

list1 = ['a','d','k','1','3','a','f','3']
list2=['1','2','3','4','5']

what my resulting list should be:

listResult=['1','3','a','f','3']

in list 1, the element '1' is found in the list2. Hence, all the items prior to '1' has to be removed. This should not be happened with element '3', as the removing process has to be break after one removal.

I have tried with the following but it only considers one given specific element. what i am trying is to not only consider one element and to consider a list of elements.

from itertools import dropwhile

list1 = ['a','d','k','1','3','a','f','3']
element = '1'

list(dropwhile(lambda x: x != element, list1))

CodePudding user response:

The in operator should be used in lambda for containment test:

>>> list(dropwhile(lambda x, s=frozenset(list2): x not in s, list1))
['1', '3', 'a', 'f', '3']

Another interesting but slightly inefficient solution:

>>> from itertools import compress, accumulate
>>> from operator import or_
>>> s = set(list2)
>>> list(compress(list1, accumulate((x in s for x in list1), or_)))
['1', '3', 'a', 'f', '3']

Because the default value of the second parameter of accumulate is equivalent to operator.add, and positive numbers are always regarded as true in Python, the or_ can be omitted:

>>> list(compress(list1, accumulate(x in s for x in list1)))
['1', '3', 'a', 'f', '3']

CodePudding user response:

We can make a set using list1 which can be used to check if item in list2 present in list1.
If it is present, we can take the index of the item and take the subarray from the item index. Then we can break the loop.

list1 = ['a','d','k','1','3','a','f','3']
list2 = ['1','2','3','4','5']
listResult = []

set1 = set(list1)
for i in list2:
    if (i in set1):
        idx = list1.index(i)
        listResult = list1[idx:]
        break

print(listResult)
  • Related