Search code examples
pythonpython-3.xpython-3.8

Remove element from list if list of sub strings in list


Fairly a newbie in Python3. Was wondering what the most efficient way is to accomplish this, i.e. if a directory listing contains a sub directory, then remove that item from the directory listing.

dirs = [ "/mnt/user/dir1", "/mnt/user/dir1/filea", "/mnt/user/dir2", "/mnt/user/dir3", "/mnt/user/dir4" ]
exclude_dirs = [ "/mnt/user/dir1", "/mnt/user/dir3" ]

if any element of exclude_dirs occurs in dirs, then remove that item from dirs. In above example, the matching would be a substring match, i.e. I'd expect these elements to be removed from dirs:

"/mnt/user/dir1"
"/mnt/user/dir1/filea"
"/mnt/user/dir3"

Help! :)

Thanks!


Solution

  • >>> [d for d in dirs if not any([
        d == e or d.startswith(f'{e}/') for e in exclude_dirs])]
    ['/mnt/user/dir2', '/mnt/user/dir4']