简体   繁体   English

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

[英]Remove string from list if from substring list

I was wondering what's the most pythonic way to: 我想知道什么是最pythonic方式:

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

Using list comprehensions 使用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 使用split获取文件名

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

you also could use a filter function with lambda 你也可以使用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) 或者如果你不介意导入os (imo这是更干净然后拆分字符串)

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]

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

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