Home > Enterprise >  How to remove a list of substrings from a list of strings
How to remove a list of substrings from a list of strings

Time:01-29

I can find lots of advice re: removing a list of substrings from a string but very little / none on removing a list of substrings from a list of strings.

My data is as such :

List 1 : [Op 18 TC 16, TC 20, OP 15 TC 80]

List 2 : [Op 18, , OP 15]

Expected result : a final list containing : [TC 16, TC 20, TC 80]

I am aware that I will need to account for spaces and such and the answer may well be obvious / staring me in the face but I just cant seem to crack this one.

I have tried for loop within a for loop but end up with the obvious multitude of values in the final list and I have tried a list comprehension that I thought would work but it had no affect.

If I need to improve the question please tell me, but please help as I am stuck on this one

CodePudding user response:

Try this:

lst1 = ['Op 18 TC 16', 'TC 20', 'OP 15 TC 80']
lst2 = ['Op 18', 'OP 15']

result = []
for s1 in lst1:
    tmp = s1
    for s2 in lst2:
        tmp = tmp.replace(s2, '')
    result.append(tmp.strip())

Here is the result

>>> result
['TC 16', 'TC 20', 'TC 80']

CodePudding user response:

You can do it by looping the second array and removing the items from the first see below:

listOne = ["Op 18", "Op 18", "TC 16", "TC 20", "OP 15", "TC 80"]
listTwo =  ["Op 18", "OP 15"]

for string in listTwo:
    try:
        while True:
            listOne.remove(string)
    except ValueError:
        pass

print(listOne)
# ['TC 16', 'TC 20', 'TC 80']

CodePudding user response:

You can use str.replace to remove the substrings in list2 found in list1 as follows:

list1 = ["Op 18 TC 16", "TC 20", "OP 15 TC 80"]
list2 = ["Op 18", "OP 15"]

list3 = []
for a in list1:
    c = a
    for b in list2:
        c = c.replace(b, '')
    
    list3.append(c.strip())

This code iterates through the strings in list1, copies the string in list1 to a variable, replaces the substring with nothing in c if it is found, strips whitespace, then appends the new string to list3.

  •  Tags:  
  • Related