Deepak B
Deepak B

Reputation: 2335

Ignore the items in the ignore list by name in python

I would like to ignore all the items in a ignore_list by name in python. For example consider

fruit_list = ["apple", "mango", "strawberry", "cherry", "peach","peach pie"]
allergy_list = ["cherry", "peach"]
good_list = [f for f in fruit_list if (f.lower() not in allergy_list)]
print good_list

I would like the good_list to ignore "peach pie" as well because peach is in the allergy list and peach pie contains peach :-P

Upvotes: 1

Views: 2395

Answers (3)

user2555451
user2555451

Reputation:

>>> fruits = ["apple", "mango", "strawberry", "cherry", "peach","peach pie"]
>>> allergies = ["cherry", "peach"]
>>> [f for f in fruits if not filter(f.count,allergies)]
['apple', 'mango', 'strawberry']
>>>

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142206

How about:

fruits = ["apple", "mango", "strawberry", "cherry", "peach","peach pie"]
allergies = ["cherry", "peach"]

okay = [fruit for fruit in fruits if not any(allergy in fruit.split() for allergy in allergies)]
# ['apple', 'mango', 'strawberry']

Upvotes: 2

Aleksander Lidtke
Aleksander Lidtke

Reputation: 2926

All you need to do is to implement something like this. It depends on the formatting of the strings that you plan on using, but it works for this example. Just add it at the end of your example code. Feel free to ask for future clarification or how to deal with other formatting of entries in fruit_list.

good_list2=[]
for entry in good_list:
    newEntry=entry.split(' ')
    for split in newEntry:
        if not split in allergy_list:
             good_list2.append(split)

 print good_list2

Upvotes: 2

Related Questions