【问题标题】:Deleting a certain kind of list elements in python using regex使用正则表达式在python中删除某种列表元素
【发布时间】:2021-12-09 10:50:31
【问题描述】:
import re

def extraction(parentTag):
    should_retain = True
    for imageTag in parentTag:
        if re.search("^(\d+.+\d)",imageTag) and not re.search("^(\d+.+\d[-^]\w)",imageTag) and not re.search("^(\d+.+\d[-^]\d)",imageTag):
            should_retain = False
            break
    if should_retain:
        return parentTag
    return None
    
expected_input = [
    ['419adf7', '1.0.22-SNAPSSHOT'],
    ['1.0.24', '82e13c1', 'master'],
    ['1.0.25-1618314650'],
    ['1.0.10', '7ad4886'],
    ['1.0.13-1589279873', 'e597811'],
    ['73a3788'],
    
]
expected_input = list(filter(None,list(map(extraction, expected_input))))
print(expected_input)

电流输出 = [['1.0.25-1618314650'], ['1.0.13-1589279873', 'e597811']]

预期输出 = [['1.0.25-1618314650'], ['1.0.13-1589279873', 'e597811'], ['419adf7', '1.0.22-SNAPSSHOT'], ['73a3788'] ]

还有没有更好的方法来编写代码以使用正则表达式获得预期输出。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    你可以使用

    import re
    rx1 = re.compile(r'^\d+\.\d+\.\d+-\w')
    rx2 = re.compile(r'^\d+\.\d+\.\d+$')
    def extraction(parentTag):
        return [x for x in parentTag if any(rx1.match(e) for e in x) or not any(rx2.match(e) for e in x)]
    
    expected_input = [
        ['419adf7', '1.0.22-SNAPSSHOT'],
        ['1.0.24', '82e13c1', 'master'],
        ['1.0.25-1618314650'],
        ['1.0.10', '7ad4886'],
        ['1.0.13-1589279873', 'e597811'],
        ['73a3788'],
    ]
    
    expected_input = extraction(expected_input)
    print(expected_input)
    

    输出:

    [['419adf7', '1.0.22-SNAPSSHOT'], ['1.0.25-1618314650'], ['1.0.13-1589279873', 'e597811'], ['73a3788']]
    

    请参阅Python demo

    注意

    • 有两种正则表达式检查:列表中必须至少有一项与^\d+\.\d+\.\d+-\w 匹配(请参阅any(rx1.match(e) for e in x)),或者必须没有一项与^\d+\.\d+\.\d+$ 模式匹配(请参阅any(rx2.match(e) for e in x))。
    • 使用您的代码,您无法访问父列表,因为您映射了列表列表map(extraction, expected_input)。您需要将列表列表作为extraction 函数的参数进行处理。

    【讨论】:

    • 您好 Wiktor,非常感谢您的帮助,它按预期工作只是怀疑如何使用已从 expected_input 中删除的元素创建新列表。
    • @SAIANURAGDODDI 只需撤销检查 - 请参阅 this demo
    【解决方案2】:

    关于最后一个问题:重构定义提取函数的复杂程度。这是一个增强功能:

    def extraction(parentTag):
        should_retain = not any(
            re.search("^(\d+.+\d)", imageTag)
            and not re.search("^(\d+.+\d[-^]\w)", imageTag)
            and not re.search("^(\d+.+\d[-^]\d)", imageTag)
            for imageTag in parentTag
        )
        if should_retain:
            return parentTag
        return None
    

    【讨论】:

    • 没有解决问题,只是后面的部分是
    猜你喜欢
    • 2019-03-15
    • 2012-07-05
    • 2013-08-14
    • 2013-02-08
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多