【发布时间】:2022-01-16 21:22:09
【问题描述】:
str_list = ['Alex is a good boy',
'Ben is a good boy',
'Charlie is a good boy']
matches = ['Charlie','good']
我想返回str_list 中的第三个元素,因为它同时包含“Charlie”和“good”。
我试过了:
[s for s in str_list if all([m in s for m in matches])][0]
但这对我来说似乎过于冗长。请提供更优雅的解决方案。
根据下面的答案和 cmets,我们有:
next(s for s in str_list if all(m in s for m in matches))
它显然更快(尽管有一点点)而且更整洁。
【问题讨论】:
-
你的解决方案对我来说看起来很优雅!
-
小点:你可以把括号放在
all(...)里面。
标签: python string match list-comprehension