data-monkey
data-monkey

Reputation: 1725

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']

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.

Upvotes: 2

Views: 1048

Answers (1)

Mandera
Mandera

Reputation: 3017

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))

Upvotes: 3

Related Questions