-3

Say I have two lists:

list1 = ['a', 'b']
list2 = ['cat', 'dog', 'bird']

Whats the best way to get rid of any items in list2 that contain any of the substrings in list1? (In this example, only 'dog' would remain.)

yellavon
  • 2,821
  • 12
  • 52
  • 66

2 Answers2

3

You can use list comprehension with any() operator. You go through the items of second list, if any of items(charachters) in list1 is in the selected word, we don't take it. Otherwise, we add it.

list1 = ['a', 'b']
list2 = ['cat', 'dog', 'bird']

print [x for x in list2 if not any(y for y in list1 if y in x)]

Output:

['dog']

You can use filter() as well.

print filter(lambda x: not any(y for y in list1 if y in x), list2)
Community
  • 1
  • 1
0

You can use regular expressions to do the job.

import re
pat = re.compile('|'.join(list1))
res = []
for str in list2:
    if re.search(pat, str):
        continue
    else:
        res.append(str)
print res
kylieCatt
  • 10,672
  • 5
  • 43
  • 51
sincosmos
  • 370
  • 2
  • 7
  • 15
  • 1
    `re` seems like overkill for a simple substring problem. – jayelm Nov 14 '14 at 00:56
  • Really? I thought regular expression is the best method to do with strings. Maybe I am wrong, thank you for pointing it out. – sincosmos Nov 14 '14 at 01:00
  • Definitely the most flexible and powerful, but the simple `in` operator is enough to check for substring membership, which is all that's required in this problem. – jayelm Nov 14 '14 at 01:00
  • @JesseMu I was trying to avoid for-loops, so I thought of re. You are right, in is enough here, ㅠㅠ. – sincosmos Nov 14 '14 at 01:04