从包含多个模式的列表中查找字符串

Find the string from a list that contains multiple patterns

str_list = ['Alex is a good boy',
            'Ben is a good boy',
            'Charlie is a good boy']
matches = ['Charlie','good']

我想 return str_list 中的第三个元素,因为它同时包含 'Charlie' 和 'good'。

我试过:

[s for s in str_list if all([m in s for m in matches])][0]

但这对我来说似乎过于冗长。请更优雅的解决方案。


根据下面的回答和评论,我们有:

next(s for s in str_list if all(m in s for m in matches))

它显然更快(但略微)和更整洁。

我会使用 filter 函数,它 returns 是一个迭代器,因此如果与 next

一起使用,它会在第一次匹配时停止
next(filter(lambda s: all(m in s for m in matches), str_list))

@Timus 建议的更清晰的方法

next(s for s in str_list if all(m in s for m in matches))