【问题标题】:What is the most pythonic way to filter list of strings with a list of regular expressions in the order of the regex?用正则表达式的顺序过滤带有正则表达式列表的字符串列表的最pythonic方法是什么?
【发布时间】:2016-10-12 22:27:32
【问题描述】:

如果我有一个字符串列表strlst 和一个正则表达式列表rexlst,那么过滤掉strlst 的每个元素的最pythonic 方法是什么,其中 none rexlst 中的正则表达式匹配?因此,只要 rexlst 中的一个常规 erpressions 与 strlst 中的一个字符串匹配,这个特定的字符串就应该包含在输出列表中。 添加的复杂性* 是,我想要 **strlst 首先 的那些元素 由 rexlst 中的第一个正则表达式匹配,然后是那些与第二个匹配的元素,依此类推

一个非常简单的例子:

import re
strlst = ['aaaaaa', '1234', 'bbbbb', '------', '.+/4-3', 'a1b2c3']
rexlst = [re.compile(x) for x in [r'^[a-z]+$', r'^\d+$']]

想要的结果是输出列表:

outlst = ['aaaaaa', 'bbbbb', '1234']

它应该适用于任何strlstreglist 的任意组合。加号是一种相当有效且简短的解决方案。

我能想到的最好的方法是:

outlist = filter(lambda x: any([True if r.match(x) else False for r in rexlst]), strlst)

但这给出了错误的顺序,即它保留了字符串在strlst中出现的顺序:

outlst = ['aaaaaa', '1234', 'bbbbb']

【问题讨论】:

    标签: python regex list filter


    【解决方案1】:

    将您的字符串列表转换为set 以便轻松删除元素,然后不断循环遍历剩余的字符串以查看正则表达式是否匹配。迭代时需要小心从集合中移除元素,所以每次都复制一份:

    tomatch = set(strlst)
    outlist = []
    for regex in rexlst:
        for value in set(tomatch):
            if regex.match(value):
                outlist.append(value)
                tomatch.remove(value)
    

    这可以转换为列表推导式,但这确实会损害可读性:

    tomatch = set(strlst)
    outlist = [v for regex in rexlst for v in set(tomatch) if regex.match(v) and not tomatch.remove(v)]
    

    即使来自strlst 的字符串匹配多个正则表达式,这些也可以工作。

    列表理解的演示:

    >>> import re
    >>> strlst = ['aaaaaa', '1234', 'bbbbb', '------', '.+/4-3', 'a1b2c3']
    >>> rexlst = [re.compile(x) for x in [r'^[a-z]+$', r'^\d+$']]
    >>> tomatch = set(strlst)
    >>> [v for regex in rexlst for v in set(tomatch) if regex.match(v) and not tomatch.remove(v)]
    ['aaaaaa', 'bbbbb', '1234']
    

    tomatch 中留下了不匹配的字符串,如果有帮助的话:

    >>> tomatch
    set(['.+/4-3', 'a1b2c3', '------'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2015-07-19
      • 2012-10-13
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多