检查列表中是否包含其他列表中的项目

时间:2019-04-10 01:13:44

标签: python python-2.7 list-comprehension

我知道以前已经有人问过这个版本,但是我找不到我想要的东西。我有两个清单。我只想打印来自 不包含来自firstList的项目的otherList中的项目。

firstList = ["ABC", "DEF"]
otherList = ["ABCfoo", "foobar", "DEFfoo", "otherFooBar"]

matching = [s for s in otherList if "ABC" not in s] #Not sure how to apply this to multiple strings in a list

所需结果:

["foobar", "otherFooBar"]

3 个答案:

答案 0 :(得分:3)

matching = [el for el in otherList if not any(substr in el for substr in firstList)]

如果您觉得更合理,则可以将not any(substr in el ...)写为all(substr not in el ...)

答案 1 :(得分:2)

进行复制并删除元素

>>> matching = otherList.copy()
>>> for a in firstList:
...     for b in matching:
...             if a in b:
...                     matching.remove(b)
... 
>>> matching
['foobar', 'otherFooBar']

答案 2 :(得分:1)

您可以使用正则表达式,

import re

pattern = '|'.join(firstList)
matching = [word for word in otherList if not re.search(pattern, word) ]

['foobar', 'otherFooBar']