简体   繁体   English

有没有办法检查列表中的字符串是否包含来自另一个列表的任何子字符串?

[英]Is there a way to check if strings in a list contain any substrings from another list?

I have two lists of strings, list_1 and list_2.我有两个字符串列表,list_1 和 list_2。

list_1 = ["Hello", "Hi", "Hey"]
list_2 = ["Hello, my name in John.", "Hi, my name is John.", "Hey, my name 
           is John.", "My name is John."]

I want to check if any of the strings in list_1 are contained in any of the strings in list_2, in such a way that returns the strings in list_2 for which this is true.我想检查 list_1 中的任何字符串是否包含在 list_2 中的任何字符串中,以这种方式返回 list_2 中的字符串,这对于它来说是正确的。 Is there a good way to do this?有没有好的方法可以做到这一点?

You can use the any function with a generator expression as a filter condition of a list comprehension:您可以使用带有生成器表达式的any函数作为列表推导式的过滤条件:

[s for s in list_2 if any(k in s for k in list_1)]

This returns:这将返回:

['Hello, my name in John.', 'Hi, my name is John.', 'Hey, my name is John.']

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

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