1

我想在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

4

3 回答 3

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
于 2013-07-17T20:05:04.367 回答
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']
于 2013-07-17T20:05:40.337 回答
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']
>>>
于 2013-07-17T20:55:25.283 回答