繁体   English   中英

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

[英]Check if List Contains Items From Another List

我知道以前曾有人问过这个版本,但是我找不到我想要的东西。 我有两个清单。 我只想打印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 ...) not any(substr in el ...)作为all(substr not in el ...)

复制并删除元素

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

您可以使用正则表达式,

import re

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

['foobar', 'otherFooBar']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM