Remove a line from the list if from the list of substrings

I was wondering what is the most pythonic way:

With a list of strings and a list of substrings, delete the items in the list of strings containing any of the subscripts.

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

Required Conclusion:

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

I tried to implement similar questions such as this , but I am still trying to do the deletion and extend this specific 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 it's probably not a cleaner way and, more importantly, it doesn't support the list, if I want to remove hello.txt or yellow.txt, I have to use a or. Thanks.

+6
source share
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 the file name

 >>> [l.split('\\')[-1] for l in list_dirs] ['hello.txt', '.world.txt', 'yellow.txt'] 
+2
source

you can also use 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 importing os (imo is cleaner and then split the lines)

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

In the understanding of the list, it will look like

 [l for l in list_dirs if os.path.basename(l) not in unwanted_files] 
+1
source

Source: https://habr.com/ru/post/982845/


All Articles