I have a list of long strings and I'd like to get the indexes of the list elements that match a substring of strings in another list. Checking if a list item contains a a single string inside a list is easy to do with list comprehensions, like this question:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
thing_to_find = "abc"
matching = [i for i, x in enumerate(my_list) if thing_to_find in x]
However, I'd like to check not only if "abc"
is in x
, but if any strings in another list are in the list, like so:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
things_to_find = ['abc', 'def']
This obviously doesn't work (but it would be really cool if it did):
matching = [i for i, x in enumerate(my_list) if things_to_find in x]
I can find the list indexes if I run commands individually, but it's tedious and horrible:
print([i for i, x in enumerate(my_list) if 'abc' in x])
# [0, 3]
print([i for i, x in enumerate(my_list) if 'def' in x])
# [1]
What's the best way to find the indexes of all instances where elements from one list are found in another list?