str_list = ['Alex is a good boy',
'Ben is a good boy',
'Charlie is a good boy']
matches = ['Charlie','good']
I want to return the third element in str_list
, because it contains both 'Charlie' and 'good'.
I have tried:
[s for s in str_list if all([m in s for m in matches])][0]
But this seems overly verbose to me. More elegant solution please.
Based on the answer and comments below, we have:
next(s for s in str_list if all(m in s for m in matches))
It's obviously faster (however marginally) and neater.
CodePudding user response:
I'd use the filter
function, it returns an iterator so it stops at first match if used with next
next(filter(lambda s: all(m in s for m in matches), str_list))
An even clearer method suggested by @Timus
next(s for s in str_list if all(m in s for m in matches))