2

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?

0

1 Answer 1

1

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)]
Sign up to request clarification or add additional context in comments.

4 Comments

list_b is a list of tuples, i am able to access the individual elements as list_b[ ][ ] but not in the loop. updated question!
Then use output = [(b,n) for a in A for b,n in B if a in b].
@lilipunk try this: output = [j for i in list_a for j in list_b if i in j[0]]
@mtilhan Thank you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.