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.
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']
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With