Skip to main content
 首页 » 编程设计

python之Python 中 2 个列表中字符串中的常见字符

2025年05月04日21dyllove98

我有 2 个列表如下:

a = ["Ron is great", "Mark is good", "Sheela is bad", "Amy is horrible"] 
b = ["Ron", "Mark"] 
c = [item for item in a if item in b] 

我通常使用上面的列表理解来查找 2 个列表之间的公共(public)元素。但是在上面的场景中它失败了,因为 IN 函数进行了精确匹配,因此 c 是一个空列表。我如何绕过这个并尝试获得一个列表 c 看起来像这样:

c=["Ron is great", "Mark is good"] 

请您参考如下方法:

例如,你需要两个循环

c = [item for item in a 
     if any(name in item for name in b)] 

应该足够了。