0

I'm trying to check whether a list of string items have substrings belong to a list of strings (desirable list) but not to another list of string (exclusion list). Here's an example below of what I'm trying to do:

worthwhile_gifts = []

wishlist = ['dog', 'cat', 'horse', 'pony']

gifts = ['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse', 'blob fish']

# Checking that various Xmas gifts include items from wishlist
for gift in gifts:
    if any(i in gift for i in wishlist):
        worthwhile_gifts.append(gift)

Looking at the result, we get what we expect this way

>>> print(worthwhile_gifts)
['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse']

Now what I'm trying to do is to check the list of gifts against the following two lists (I want items form wishlist but not from blocklist) and I'm having a hard time generating the if statement condition with two any statements in it

wishlist = ['dog', 'cat', 'horse', 'poney']
blocklist = ['bulldog', 'caterpillar', 'workhorse']

# Expected result would exclude 'bulldog'
>>> print(worthwhile_gifts)
['a dog', 'a cartload of cats', 'Mickey doghouse']

Any idea how to construct this if statement? I tried if (any(i in gift for i in wishlist)) and (any(i in gift for i not in blocklist)) but this doesn't work.

FinanceGardener
  • 188
  • 2
  • 17

1 Answers1

2

You're close, you need to check that the gift is not in the blacklist (all & not int)

wishlist = ['dog', 'cat', 'horse', 'poney']
blocklist = ['bulldog', 'caterpillar', 'workhorse']

gifts = ['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse', 'blob fish']

worthwhile_gifts = []

for gift in gifts:
    if any(i in gift for i in wishlist) and all(i not in gift for i in blocklist):
        worthwhile_gifts.append(gift)

print(worthwhile_gifts)

Result:

['a dog', 'a cartload of cats', 'Mickey doghouse']
rdas
  • 20,604
  • 6
  • 33
  • 46
  • Thanks @rdas - this works perfect. Checking this other post really helped me understand why I needed to resort to `all` in the second statement: https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work – FinanceGardener Jul 19 '20 at 17:26