Friday, 13 September 2013

Python: How to remove items from a list that contains words found in items in another list

Python: How to remove items from a list that contains words found in items
in another list

I want to remove items from list 'a' where list 'b' contains items with
words found in list 'a'
a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']
The result should be:
a = ['seven eight nine']
This because the words 'two' and 'five six' are found in items in list 'a'.
This is how I have tried to solve it:
for i in a:
for x in b:
if x in i:
a.remove(i)
This returns:
print a
['four five six', 'seven eight nine']
Why does this not work, and how can I solve this problem?
Thanks.

No comments:

Post a Comment