如果从子字符串列表中删除列表中的字符串

dud*_*das 6 python string numpy substring list

我想知道什么是最pythonic方式:

拥有字符串列表和子字符串列表会删除包含任何子字符串列表的字符串列表的元素.

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

unwanted_files = ('hello.txt', 'yellow.txt)
Run Code Online (Sandbox Code Playgroud)

期望的输出:

list_dirs = (C:\\bar\\foo\.world.txt')
Run Code Online (Sandbox Code Playgroud)

我曾试图实施类似的问题,比如这个,但我仍然在努力使去除和特定的实现扩展到一个列表.

到目前为止,我已经这样做了:

for i in arange(0, len(list_dirs)):
    if 'hello.txt' in list_dirs[i]:
        list_dirs.remove(list_dirs[i])
Run Code Online (Sandbox Code Playgroud)

这可行,但可能不是更清洁的方式,更重要的是它不支持列表,如果我想删除hello.txt或yellow.txt我将不得不使用或.谢谢.

sty*_*ane 2

使用list comprehensions

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

用于split获取文件名

>>> [l.split('\\')[-1] for l in list_dirs]
['hello.txt', '.world.txt', 'yellow.txt']
Run Code Online (Sandbox Code Playgroud)