繁体   English   中英

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

[英]Remove string from list if from 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)

期望的输出:

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

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

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

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

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

使用list comprehensions

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

使用split获取文件名

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

你也可以使用lambda的过滤函数

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

或者如果你不介意导入os (imo这是更干净然后拆分字符串)

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

在列表理解中,它看起来像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM