python - 将子字符串列表匹配到 Python 中的字符串列表

标签 python string-matching

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

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:

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

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

是否有更好的方法(比如库函数)来吸收其中一个维度?

非常感谢。

最佳答案

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

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

关于python - 将子字符串列表匹配到 Python 中的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234965/

相关文章:

python - Buildbot 不以默认配​​置启动

string - 解决局部对齐的算法

java - 使用正则表达式在字符串中搜索子字符串

javascript - Seleniumexecute_script 将 "AI"添加到函数中

Python:我可以安全地解开不受信任的数据吗?

python - 机器人框架访问测试套件元数据中的关键字

mysql - 给定一串单词 : How to find every word (case insensitive) in a varchar(1000) column in MySQL ignoring punctuation?

python - 当遇到特定单词时分割字符串

javascript - 正则表达式强制特定 3 个字符

python - 用python解析并重写文件