簡體   English   中英

Python:如何將功能合而為一

[英]Python: How do I combine functions to one

我是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)

首先,這里您實際上不需要兩個if語句。 如果該行不包含etxe ,則它將不匹配任何一個正則表達式,因此您可以簡化它。

其次,您的if value or value_xe:是有意義的-但隨后您僅在下面的代碼中使用value ,而沒有使用。 您需要使用匹配的任何一個。 解決此問題的最簡單方法是只使用or的結果。 在Python中,如果x or y是真實的,則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)

如果您將兩個正則表達式“合並”為一個,則可能也更簡潔:

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)

問號會創建一個所謂的“非捕獲組”,並且管道將兩種選擇組合在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM