Reputation: 183
I have two lists, one of which has substrings of the other list. I want to pull all rows from List B which have matching substrings in list A.
For example, List A:
Sally Hope
Bob John
Seth Whale
List B
[('Sally Hope does not like chocolate', 14)
('Sally Hope is great', 45)
('Seth Whale likes swimming', 43)
('Marley does not like walks', 56)
('John goes on walks', 55)]
Output:
[('Sally Hope does not like chocolate', 14)
('Sally Hope is great', 45)
('Seth Whale likes swimming', 43)]
I've tried this in R with amatch and dpylr filter but did not get the desired output and R fails me on memory (list B has ~2m rows). What is the most efficient way to do this in python?
Upvotes: 2
Views: 5354
Reputation: 16081
Python have list comprehension
,
output = [j for i in list_a for j in list_b if i in j[0]]
Result
[('Sally Hope does not like chocolate', 14),
('Sally Hope is great', 45),
('Seth Whale likes swimming', 43)]
Upvotes: 1