将子字符串列表与 Python 中的字符串列表匹配 [英] matching list of substrings to a list of strings in Python

查看:72
本文介绍了将子字符串列表与 Python 中的字符串列表匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将子字符串列表与字符串列表匹配的好的pythonic方法是什么,如下所示:

What is a good pythonic way to match a list of substrings to a list of strings, like the following:

if 'sub1' in str1 or 'sub2' in str1 or ... 'subN' in str1 or\
   'sub1' in str2 or 'sub2' in str2 or ... 'subN' in str2 or\
   ...
   'sub1' in strM or 'sub2' in strM or ... 'subN' in strM:

一种方法是将它们与列表理解结合起来,如下所示:

One way is to unite them with list comprehension, like this:

strList = [str1, str2, ..., strM]
subList = ['sub1', ..., 'subN']
if any(sub in str for sub in subList for str in strList):

有没有更好的东西,比如库函数,来吸收其中的一个维度?

Is there anything better, like a library function perhaps, to absorb one of the dimensions?

非常感谢.

推荐答案

您可以将子字符串编译为正则表达式,并使用它来搜索每个字符串.如果您没有太多子字符串以至于 RE 超出内部限制,这可能是最有效的方法.

You could compile the substrings into a regular expression, and use that to search each string. If you don't have so many substrings that the RE exceeds internal limits, this is probably the most efficient way.

pattern = "|".join(re.escape(s) for s in subList)
crexp = re.compile(pattern)
if any(crexp.search(s) for s in strList):
    ...

这篇关于将子字符串列表与 Python 中的字符串列表匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆