2013-07-17 51 views
1

在忽略列表中的项目的名字,我想忽略所有在ignore_list在Python中的项目的名字。例如,考虑忽略蟒蛇

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

+1

是否 “无可指责的卷子” 含有桃花? – DSM

+0

@DSM你吃什么样的餐馆? :) –

+0

是的,它确实:-( –

回答

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

'[F在水果f若没有任何(一个在f.split()在过敏的)]' – dansalmo

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