Reputation: 8025
I have a list of words in l
that if any of it exists in the first index of each tuple in l2, remove the entire tuple.
my code:
l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]
l3 = [k for k in l2 if not any(i in k[0] for i in l) ]
somehow the code does not work and i get back an empty list for l3.
I want
l3 = [('looking for me', 'please hold')]
Upvotes: 1
Views: 74
Reputation: 23743
Sets make membership testing easy. Use a function to filter your list.
import operator
first = operator.itemgetter(0
l = ['hi', 'thanks', 'thank', 'bye', 'ok', 'yes', 'okay']
l2 = [('hi how are u', 'doing great'), ('looking for me', 'please hold')]
def foo(t, l = set(l)):
t = set(first(t).split())
return bool(l & t)
l3 = [thing for thing in l2 if not foo(thing)]
Upvotes: 0
Reputation: 11476
Split k[0]
to get a list of words:
[k for k in l2 if not any(i in k[0].split() for i in l)]
This way it checks if i
matches a word exactly.
It could also be interpreted as if k[0]
does not starts with any of l
, then you can do this:
[k for k in l2 if not k[0].startswith(tuple(l))]
Upvotes: 4