Python 用于从列表中查找和排除多个匹配项的逻辑

Python 用于从列表中查找和排除多个匹配项的逻辑,python,logic,Python,Logic,我需要将列表的内容与给定的模式相匹配,并形成另一个列表,该列表将包含除匹配项之外的所有内容。也就是说,我正在尝试制作一个排除列表 现在只要一个模式匹配,就很容易了。但对于更多的人来说,这变得很棘手 让我们看一个例子: Lmain=[arc123, arc234,xyz111,xyz222,ppp999,ppp888] for count in range(len[Lmain]): if Pattern matches Lmain[i]: Pass

我需要将列表的内容与给定的模式相匹配,并形成另一个列表,该列表将包含除匹配项之外的所有内容。也就是说,我正在尝试制作一个排除列表

现在只要一个模式匹配,就很容易了。但对于更多的人来说,这变得很棘手

让我们看一个例子:

Lmain=[arc123, arc234,xyz111,xyz222,ppp999,ppp888]

for count in range(len[Lmain]):

    if Pattern matches Lmain[i]:
              Pass
    else:result.append(Lmain[i])
现在让我们假设pattern=arc,我的结果是

result = [xyz111,xyz222,ppp999,ppp888]
这只是一个逻辑,我将使用正则表达式查找匹配项

现在,如果我们有两种模式,那么在循环中使用上述逻辑:

Pattern=['arc','xyz']

for pat in Pattern:
      if pat matches Lmain[i]:
          Pass
      else:result.append(Lmain[i])
这会给我们错误的结果

result = [xyz111,xyz222,ppp999,ppp888,arc123,arc234,ppp999,ppp888]
所以,你可以看到上面的逻辑是行不通的

我的计划:

首先,我们找到第一个模式的排除列表,该列表将给出结果:

result = [xyz111,xyz222,ppp999,ppp888]
对于第二种模式,我们需要查看上面的结果

if Pattern matches Result[i]:
      Pass
else:result_final.append(Result[i])
我认为我们需要使用递归来实现上述逻辑。现在我们该怎么做? 我们也不知道用户将要输入的模式数。它可以是一个或多个

任何人有任何逻辑想法,请分享

matched = False
for pat in Pattern:
    if pat patches Lmain[i]:
        matched = True
        break;
if matched:
    Pass
else:
    result.append(Lmain[i])
将中的
替换为对您的情况更合适的内容(例如
项.startswith(pat)

如果匹配项多于非匹配项,则首先查找匹配项,然后将其排除应更有效:

matches = [x for x in lst if any(x.startswith(p) for p in patterns)]
exclude_list = list(set(lst).difference(matches))
另一个(可能是最快的)选择是使用正则表达式(这里与
过滤器结合使用):


使用列表理解和生成器表达式,并跳过构建排除列表和仅构建最终列表的中间步骤:

>>> import re
>>> Lmain=['arc123', 'arc234', 'xyz111', 'xyz222','ppp999','ppp888']
>>> Pattern=['arc','xyz']
>>> [x for x in Lmain if not any(re.search(y, x) for y in Pattern)]
['ppp999', 'ppp888']

你能为你的例子使用真正的python代码吗?+1,也可以用一行:
exclude_list=[如果所有,则lst中的项目(pat不在项目中,pat在模式中)]
@eumiro,是的,这是Wooble写的,但我发现在这种情况下,compr可读性较差。
import re
expr = '^(?!%s)' % '|'.join(patterns)
exclude_list = filter(re.compile(expr).search, lst)
>>> import re
>>> Lmain=['arc123', 'arc234', 'xyz111', 'xyz222','ppp999','ppp888']
>>> Pattern=['arc','xyz']
>>> [x for x in Lmain if not any(re.search(y, x) for y in Pattern)]
['ppp999', 'ppp888']