Skip to main content
 首页 » 编程设计

python之列表理解 : retrieve valid strings if not contained in a list of substrings

2025年05月04日22wayfarer

我需要检查是否可以复制文件名列表,并根据禁止的子字符串列表检查它。

这是我的:

exclude = ['ex','xe'] 
files = ['include', 'exclude'] 

这就是我所期望的:

['include'] 

我已经让它与列表推导一起工作,像这样:

[a[0] for a in [(f, any([e in f for e in exclude])) for f in files] if not a[1]] 

我在其中创建一个元组 (f, any([e in f for e in exclude])) 检查文件名是否与排除的子字符串有任何对应关系。 我对文件列表中的每个文件执行此操作 for f in files 并且仅包括那些不存在于排除子字符串 if not a[1] 中的文件。

有更好的方法吗?一个更pythonic的? 因为我在文件列表中循环了 2 次,我猜想有一种方法可以一次性完成!

谢谢!

请您参考如下方法:

我不太明白你的逻辑。看起来您正在使用 bool 值构建元组,然后过滤掉 False 值。

在我看来,这也行得通而且更简单:

exclude = ['ex','xe'] 
files = ['include', 'exclude'] 
 
print([x for x in files if not any(e in x for e in exclude)]) 

它遍历 files,并且对于每个文件,检查其中没有包含 exclude 成员。

请注意,您不必在 any 中构建实际列表。省略方括号,让 any 执行惰性求值,速度更快。