1

I have a list of curse words I want to match against other list to remove matches. I normally use list.remove('entry') on an individual basis, but looping through a list of entries against another list - then removing them has me stumped. Any ideas?

ewhitt
  • 897
  • 1
  • 12
  • 18

2 Answers2

10

Using filter:

>>> words = ['there', 'was', 'a', 'ffff', 'time', 'ssss']
>>> curses = set(['ffff', 'ssss'])
>>> filter(lambda x: x not in curses, words)
['there', 'was', 'a', 'time']
>>> 

It could also be done with list comprehension:

>>> [x for x in words if x not in curses]
Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
4

Use sets.

a=set(["cat","dog","budgie"])
b=set(["horse","budgie","donkey"])
a-b
->set(['dog', 'cat'])
Jay M
  • 3,736
  • 1
  • 24
  • 33
  • What if I already have the lists define? Could I do: a = ['bad_word1', 'bad_word2' ] b = ['a', 'b', 'bad_word1' ] set1 = set(a) set2 = set(b) set1 - set2 a = set1 b = set2 – ewhitt May 11 '12 at 22:50
  • notice that sets could mess the order of the words and also would remove duplicate words from your list. Also it should be faster I guess. – Facundo Casco May 11 '12 at 22:56