aquaticdigest
aquaticdigest

Reputation: 37

How to remove a substring in a fullstring without deleting any other element that matches the substring

I have 2 lists. How do I remove a substring in list2 exists in list1?

list1 = ['123foo, 134foo', '124bar', '1123foo']
list2 = ['123foo', '124bar']

This is what I am expecting:

expectedlist1 = ['134foo', '1123foo']

I have so far done this to find the substring in fullstring, and to remove the substring but unfortunately the result is not what I am expecting.

def removesubstring(list1, list2):
    for x in range(len(list2)):
        for y in range(len(list1)):
            if search(list2[x],list1[y]):
                list1[y] = list1[y].replace(list2[x], "")
    list1= list(filter(None, list1)) #To remove the empty strings from the list
    return list1, list2

What I am getting after running my code:

resultinglist = [', 134foo', '1']

The reason for not flattening the list is that the indexes of the list would change. The indexes of the list are important to maintain as they are referring another list with the same length. If there is a way to unflatten it to the original length then it is welcomed (but im not sure if its possible)

Upvotes: 0

Views: 36

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19395

  • For efficiency, convert list2 to a set.
  • Iterate over list1:
    • split each string on ", " and remove elements which are in list2.
    • join back the leftover strings with ", "
    • Add to the result list.
list1 = ['123foo, 134foo', '124bar', '1123foo']
list2 = ['123foo', '124bar']

set2 = set(list2)
res = []
for s in list1:
    leftovers = [part for part in s.split(', ') if part not in set2]
    if leftovers:  # To avoid adding an empty string
        res.append(', '.join(leftovers))

print(res)

Gives:

['134foo', '1123foo']

Upvotes: 1

Related Questions