在python中按名称忽略忽略列表中的项目

时间:2013-07-17 19:55:04

标签: python list python-2.7

我想在python中按名称忽略ignore_list中的所有项。例如,考虑

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

我希望good_list也能忽略“桃子馅饼”,因为桃子在过敏列表中,而桃子馅饼中含有桃子:-P

3 个答案:

答案 0 :(得分:2)

你需要做的就是实现这样的事情。它取决于您计划使用的字符串的格式,但它适用于此示例。只需在示例代码的末尾添加它即可。请随意询问以后的说明或如何处理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

答案 1 :(得分:2)

怎么样:

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']

答案 2 :(得分:1)

>>> 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']
>>>