Python:如何将功能合而为一

时间:2018-08-13 19:38:56

标签: python

我是python的新手。 需要帮助将以下代码作为一个代码块编写,而不是使用基于值的if语句。

    for lines in f:                                                     

        if 'et' in lines:
            # print lines
            value = re.search('(et-\d\\/\d\\/\d)', lines)
            if value:
                interfaces = value.group(1)
                # print interfaces
                smic_dict.setdefault(pfe, []).append(interfaces)        
                pfe_interfaces.append(interfaces)

        if 'xe' in lines:
            value_xe = re.search('(xe-\d\\/\d\\/\d)', lines)
            if value_xe:
                interfaces_xe = value_xe.group(1)
                smic_dict.setdefault(pfe, []).append(interfaces_xe) 
                pfe_interfaces.append(interfaces_xe)

到目前为止已经尝试过:

        for lines in temp:
        if 'et' or 'xe' in lines:
            value = re.search('(et-\d\\/\d\\/\d)', lines)
            value_xe = re.search('(xe-\d\\/\d\\/\d)', lines)
            if value or value_xe:
                interfaces = value.group(1)
                pic_interfaces.append(interfaces)

2 个答案:

答案 0 :(得分:1)

首先,您在这里实际上不需要两个if语句。如果该行不包含etxe,则该行将不匹配任何一个正则表达式,因此您可以简化它。

第二,您的if value or value_xe:是有道理的-但您在下面的代码中仅使用value,而没有用。您需要使用匹配的任何一个。解决此问题的最简单方法是仅使用or的结果。在Python中,如果x or y为真,则表示x(在这种情况下,表示存在匹配项,而不是None),否则为y。因此,如果第一个搜索匹配,您将得到结果匹配。如果不匹配,则第二次搜索匹配,您将得到结果匹配;如果没有,您将得到None

虽然我们是次要的,但从文件lines而不是line调用仅占一行的变量有点令人困惑。

所以:

for line in temp:
    value_et = re.search('(et-\d\\/\d\\/\d)', line)
    value_xe = re.search('(xe-\d\\/\d\\/\d)', line)
    value = value_et or value_xe
    if value:
        interfaces = value.group(1)
        pic_interfaces.append(interfaces)

您可以做一些进一步改进它的事情:

  • 使用\d表示文字反斜杠字符和d字符有效,但这仅是因为\d在Python中碰巧不是转义序列(至少从3.7开始)。您真的不应该依赖于此。最好做\\d
  • 使用原始字符串文字,这样您就不必在一开始就逃脱反斜杠。
  • 您的捕获组就是您的整个表情,因此您根本不需要捕获组。只需去除括号,然后使用整个group()而不是group(1)
  • 由于您要完全相同地对待这两个结果,因此您可能希望通过使用以下替换将两个正则表达式合并为一个:match etxe,其拼写为|
    • 如果您不进行以前的更改,则希望将其设为不捕获的组,例如(?:et|xe)。但是,如果您只使用完整匹配,则不需要。

所以:

for line in temp:
    value = re.search(r'(et|xe)-\d\/\d\/\d', line)
    if value:
        interfaces = value.group()
        pic_interfaces.append(interfaces)

答案 1 :(得分:1)

如果您将两个正则表达式“合并”为一个,您也可能会更加凝缩:

for lines in f:
    value = re.search('((?:et|xe)-\d\\/\d\\/\d)', lines)
    if value:
        interfaces = value.group(1)
        # print interfaces
        smic_dict.setdefault(pfe, []).append(interfaces)
        pfe_interfaces.append(interfaces)

问号会创建一个所谓的非捕获组,并且管道将这两种选择组合在一起。