Skip to main content
 首页 » 编程设计

python之检查列表是否包含另一个列表中的项目

2025年05月04日13me-sa

我知道以前有人问过这个版本,但我找不到我要找的东西。我有两个列表。我只想打印 otherList 中不包含 firstList 中的项目的项目。

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

请您参考如下方法:

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 ...) 如果这对你来说更有意义。