How can I remove certain strings from a list based on the strings in another list, if those strings differ slightly? More info below

Viewed 39

This seems like a pretty rudimentary question, but I'm wondering because the items in these lists change every so often when a website is scraped...

employees = ['leadership(x)', 'drivers(y)', 'trainers(z)']

Where x,y,z are the number of employees in those specific roles, and are the values that change every so often.

If I know that the strings will always be 'leadership' 'drivers' and 'trainers', just with a difference in what's in between the parentheses, how can I dynamically remove these strings without having to hardcode it every week that I run the program?

The obvious but not so successful solution is...

employees = ['leadership(x)', 'drivers(y)', 'trainers(z)']
unwanted = ['leadership(x)', 'drivers(y)', 'trainers(z)']

for i in unwanted:
    if i in employees:
        employees.remove(i)

This of course fails because the values are hardcoded and the values are bound to change, any help with this would be greatly appreciated!

1 Answers

You could do something like

unwanted_prefixes = ['leadership', 'drivers', 'trainers']
unwanted = [s for s in employees if s.split('(')[0] in unwanted_prefixes]

This will make the list of things to delete contain any string beginning with those 3 prefixes and either containing nothing else or immediately followed by a parenthesis.

A more complicated solution, if that one deletes strings that you want, that follows roughly the same idea, but with a regex:

import re
unwanted_re = re.compile(r'(leadership|drivers|trainers)\(\d+\)')
unwanted = [x for x in employees if unwanted_re.fullmatch(x)]
Related