Reputation: 225
I'd like to find if a list of substrings is contained in a list. For example, I have:
string_list = ['item1', 'item2', 'subject3', 'subject4']
and list of substrings
substrings = ['item', 'subject']
I'd like to find if 'item' or 'subject' are included in any item of string_list. Individually, I would do something like:
any('item' in x for x in string_list)
This works for one substring but I would like to find a pretty way of searching for both strings in the list of substrings.
Upvotes: 8
Views: 6673
Reputation: 71451
You can try this:
string_list = ['item1', 'item2', 'subject3', 'subject4']
substrings = ['item', 'subject']
any(any(b in i for b in substrings) for i in string_list)
Output:
True
Upvotes: 1
Reputation: 78556
Since the substrings are actually at the start, you can use str.startswith
which can take a tuple of prefixes:
any(x.startswith(('item', 'subject')) for x in string_list)
Upvotes: 2