Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

  • For efficiency, convert list2 to a set.
  • Iterate over list1.
    • split each string on ", " and remove elements which are in list2.
    • join 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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading