Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove string from list if from substring list

I was wondering what's the most pythonic way to:

Having a list of strings and a list of substrings remove the elements of string list that contains any of the substring list.

list_dirs = ('C:\\foo\\bar\\hello.txt', 'C:\\bar\\foo\\.world.txt', 'C:\\foo\\bar\\yellow.txt')

unwanted_files = ('hello.txt', 'yellow.txt)

Desired output:

list_dirs = (C:\\bar\\foo\.world.txt')

I have tried to implement similar questions such as this, but I'm still struggling making the removal and extend that particular implementation to a list.

So far I have done this:

for i in arange(0, len(list_dirs)):
    if 'hello.txt' in list_dirs[i]:
        list_dirs.remove(list_dirs[i])

This works but probably it's not the more cleaner way and more importantly it does not support a list, if I want remove hello.txt or yellow.txt I would have to use a or. Thanks.

like image 314
dudas Avatar asked Feb 22 '15 10:02

dudas


2 Answers

Using list comprehensions

>>> [l for l in list_dirs if l.split('\\')[-1] not in unwanted_files]
['C:\\bar\\foo\\.world.txt']

Use split to get filename

>>> [l.split('\\')[-1] for l in list_dirs]
['hello.txt', '.world.txt', 'yellow.txt']
like image 63
styvane Avatar answered Oct 15 '22 04:10

styvane


you also could use a filter function with lambda

print filter(lambda x: x.split('\\')[-1] not in unwanted_files, list_dirs)
#['C:\\bar\\foo\\.world.txt']

or if you don't mind to import os (imo this is cleaner then splitting the string)

print filter(lambda x: os.path.basename(x) not in unwanted_files, list_dirs)

In a list comprehension it would look like this

[l for l in list_dirs if os.path.basename(l) not in unwanted_files]
like image 41
kasper Taeymans Avatar answered Oct 15 '22 03:10

kasper Taeymans